trait NotNull {}
我一直在尝试查看此特征如何保证某些内容不为空,但我无法弄清楚:
def main(args: Array[String]) {
val i = List(1, 2)
foo(i) //(*)
}
def foo(a: Any) = println(a.hashCode)
def foo(@NotNull a: Any) = println(a.hashCode) //compile error: trait NotNull is abstract
def foo(a: Any with NotNull) = println(a.hashCode) //compile error: type mismatch at (*)
和:
val i = new Object with NotNull //compile-error illegal inheritance
显然有一些特殊的编译器处理正在进行,因为它编译:
trait MyTrait {}
def main(args: Array[String]) {
val i: MyTrait = null
println(i)
}
而这不是:
def main(args: Array[String]) {
val i: NotNull = null //compile error: found Null(null) required NotNull
println(i)
}
编辑: 我在 Scala 编程中找不到任何关于此的内容