import shapeless._, syntax.singleton._
scala> 1.narrow
res3: Int(1) = 1
我尝试编写一个函数,给定单个1
,即根据上述内容,返回???
:
scala> def f(a: Int(1)): Unit = ???
<console>:1: error: ')' expected but '(' found.
def f(a: Int(1)): Unit = ???
^
<console>:1: error: '=' expected but ')' found.
def f(a: Int(1)): Unit = ???
^
但它无法编译。
1.narrow
的类型是什么?如何在函数中使用它?
答案 0 :(得分:4)
您可以将此类型与shapeless.Witness
语法一起使用:
def f(a: Witness.`1`.T): Unit = ???
val a = 1.narrow
f(a) // compiles
val b = 2.narrow
f(b) // type mismatch; found: Int(2) required: Int(1)
val c = 1
f(c) // type mismatch; found: c.type (with underlying type Int) required: Int(1)
还有一个Typelevel Scala编译器分支,它支持类型中的文字(使用适当的compiler flag):
def f(a: 1): Unit = ???