12
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 编程中找不到任何关于此的内容

4

2 回答 2

19

NotNull 尚未完成。目的是将其演变成一种可用的方法来检查非空性,但它还没有。暂时我不会使用它。我没有具体的预测何时完成,只是它不会在 2.8.0 到来。

于 2010-03-04T22:42:50.460 回答
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

这仅适用于 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

以及 Scala 语言参考:

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

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

于 2010-02-25T16:21:38.787 回答