“1.narrow”的类型

Type of '1.narrow'

正在查看Singleton Types

import shapeless._, syntax.singleton._

scala> 1.narrow
res3: Int(1) = 1

我试图编写一个函数,给定一个单例 1,即根据上述,return ???:

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 branch, that supports literals in types (with the appropriate compiler flag):

def f(a: 1): Unit = ???