How does the NotNull trait work in 2.8 and does anyone really use it?

trait NotNull {} 

I am trying to understand how this trait can guarantee that something is not null, and I cannot understand:

 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 

Obviously, there is some special compiler handling, because it compiles:

 trait MyTrait {} def main(args: Array[String]) { val i: MyTrait = null println(i) } 

If this is not the case:

 def main(args: Array[String]) { val i: NotNull = null //compile error: found Null(null) required NotNull println(i) } 

EDIT: there is nothing about it I can find in programming in Scala

+12
scala nullable
Feb 25 2018-10-25T00
source share
2 answers

Attempt and error:

 scala> class A extends NotNull defined class A scala> val a : A = null <console>:5: error: type mismatch; found : Null(null) required: A val a : A = null ^ scala> class B defined class B scala> val b : B = null b: B = null 

This only works with Scala 2.7.5:

 scala> new Object with NotNull res1: java.lang.Object with NotNull = $anon$1@39859 scala> val i = new Object with NotNull i: java.lang.Object with NotNull = $anon$1@d39c9f 

And the Scala Language Reference:

If this element is of type that matches scala.NotNull, members must be initialized to a non-zero value, otherwise scala. An initialization of Error is called.

For each type of class T such that T <: scala.AnyRef, and not T <: scala.NotNull, one has scala.Null <: T.

+5
Feb 25 '10 at 16:21
source share

NotNull is not finished yet. The goal is to turn this into a useful way to test for nonemptiness, but it does not exist yet. At the moment I will not use it. I have no specific predictions when this will be done, only that it will not arrive at 2.8.0.

+19
Mar 04 '10 at
source share



All Articles