NotNull特性如何在2.8中工作,是否有人真正使用它?

oxb*_*kes 12 scala nullable scala-2.8

trait NotNull {}
Run Code Online (Sandbox Code Playgroud)

我一直试图看看这个特性如何保证某些东西不是空的我无法弄清楚:

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 (*)
Run Code Online (Sandbox Code Playgroud)

和:

val i = new Object with NotNull //compile-error illegal inheritance
Run Code Online (Sandbox Code Playgroud)

显然有一些特殊的编译器处理正在进行,因为它编译:

trait MyTrait {}

def main(args: Array[String]) {
  val i: MyTrait = null
  println(i)
}
Run Code Online (Sandbox Code Playgroud)

然而,这不是:

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

编辑: 我在Scala的编程中找不到这个

Mar*_*sky 19

NotNull尚未完成.目的是将其演变为检查非零值的可用方法,但它尚未存在.目前我不会用它.我没有具体的预测,只有它不会到达2.8.0.

  • 我是否正确地说它自2.5以来一直在图书馆/语言中?它并不能很好地反映出scala中的某些功能无法正常工作. (6认同)

Tho*_*ung 5

尝试和错误:

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
Run Code Online (Sandbox Code Playgroud)

这仅适用于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
Run Code Online (Sandbox Code Playgroud)

和Scala语言参考:

如果该成员具有符合scala.NotNull的类型,则该成员的值必须初始化为不同于null的值,否则抛出scala.UnitializedError.

对于每个类类型T,使得T <:scala.AnyRef而不是T <:scala.NotNull一个具有scala.Null <:T.

  • 那么推论就是.为什么scala自己的类(例如`List`不会扩展`NotNull`特性? (2认同)