Get type of a “singleton type”

后端 未结 2 886
醉酒成梦
醉酒成梦 2021-02-15 15:47

We can create a literal types via shapeless:

import shapeless.syntax.singleton._
var x = 42.narrow
// x: Int(42) = 42

But how can I operate wit

2条回答
  •  滥情空心
    2021-02-15 16:08

    Int(42) is not a valid Scala syntax for type.

    IIRC singleton types were implemented in scalac for a while, but programmers had no syntax of defining such. Shapeless provides that, with macros, as well as some extra machinery.

    In particular, shapeless.Witness is an object that contains both type information and associated value, and also can be summoned from either.

    import shapeless.Witness
    import shapeless.syntax.singleton._
    import shapeless.test.illTyped // test string for causing type-errors when compiled
    
    // --- Type aliases ---
    val w = 42.witness
    type Answ1 = w.T // that is your Int(42) singleton type
    type Answ2 = Witness.`42`.T // same, but without extra variable
    implicitly[Answ1 =:= Answ2] // compiles, types are the same
    
    // --- Value definitions ---
    val a: Answ1 = 42 // compiles, value OK, and no need to `narrow`
    illTyped { "val b: Answ1 = 43" } // would not compile
    val c: Witness.`43`.T = 43 // that syntax is OK here too
    
    // --- Summoning values ---
    val answ = Witness[Answ1].value // will not compile for non-singleton
    def genericSingletonMethod[A](implicit W: Witness.Aux[A]) = s"Summoning ${W.value}"
    assert { genericSingletonMethod[Answ1] == "Summoning 42" }
    assert { genericSingletonMethod[Witness.`"string"`.T] == "Summoning string" }
    

提交回复
热议问题