2017-06-23 3 views
2

bei Singleton Types Blick:Typ '1.narrow'

import shapeless._, syntax.singleton._ 

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

ich versucht, eine Funktion zu schreiben, die angesichts eines Singletons 1, dh je die oben kehren ???:

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 = ??? 
      ^

Aber Es konnte nicht kompiliert werden.

Was ist der Typ von 1.narrow und wie kann ich es in einer Funktion verwenden?

Antwort

4

Sie diese Art mit shapeless.Witness Syntax verwenden:

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) 

Es gibt auch einen Typelevel Scala Compiler Zweig, die Literale in Typen (mit den entsprechenden compiler flag) unterstützt:

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