我在想是否可以在Scala中定义类型如NegativeNumber
。这种类型将是一个负数,它将由编译器同样进行检查,以整型,字符串等基于Scala约束的类型和文字
val x: NegativeNumber = -34
val y: NegativeNumber = 34 // should not compile
同样:
val s: ContainsHello = "hello world"
val s: ContainsHello = "foo bar" // this should not compile either
我可以使用这些类型,就像其他类型,例如:
def myFunc(x: ContainsHello): Unit = println(s"$x contains hello")
这些约束类型可以由临时类型(Int,String)支持。
是否可以实现这些类型(可能与宏)?
自定义文字怎么样?
val neg = -34n //neg is of type NegativeNumber because of the suffix
val pos = 34n // compile error