trait NotNull {}
I've been trying to see how this trait can guarantee that something is not null and I can't figure it out:
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 (*)
And:
val i = new Object with NotNull //compile-error illegal inheritance
There is obviously some special compiler treatment going on because this compiles:
trait MyTrait {}
def main(args: Array[String]) {
val i: MyTrait = null
println(i)
}
Whereas this does not:
def main(args: Array[String]) {
val i: NotNull = null //compile error: found Null(null) required NotNull
println(i)
}
EDIT: there's nothing about this I can find in programming in Scala
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…