查看 Singleton Types :
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
的类型是什么以及如何在函数中使用它?
最佳答案
您可以通过 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 = ???
关于scala - '1.narrow' 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44728064/