scala - '1.narrow' 的类型

标签 scala shapeless

查看 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/

相关文章:

java - 如何在 Go SBT 任务中指定 JVM 标志?

scala - 无形 : Checking of the Type Constraints of Polymorphic Functions (lifted types)

scala - 子集和无形可扩展记录

scala - 避免按类型过滤实例

scala - Spark序列化错误之谜

scala - 什么是 `path.home` 变量以及如何设置它?

scala - 如何映射 Nat 的无形 HList

scala - 无形:Generic.Aux

data-structures - 如何从Scala中的文件读取不可变数据结构

scala - List[_] 中扩展函数缺少参数类型