Nothing
is - together with scala.Null - at the bottom of Scala's type hierarchy.
Scala中的Nothing和Null两个类位于Scala类型继承树的底部。
Nothing
is a subtype of every other type (including scala.Null); there exist no instances of this type.
Nothing是Scala中其他任何类(包含Null)的子类,Nothing不能再被子类化。
Although type Nothing
is uninhabited, it is nevertheless useful in several ways.
Nothing在几个方面发挥作用。
For instance, the Scala library defines a value scala.collection.immutable.Nil of type List[Nothing]
.
比如,Scala用Nil定义空集合,而Nil其实是List[Nothing]
Because lists are covariant in Scala, this makes scala.collection.immutable.Nil an instance of List[T]
, for any element of type T
.
因为Scala中的列表是协变的,所以Nil是任何泛型列表List[T]的实例,而只有Nothing是所有类型T的子类,所以在
定义Nil的时候,Nothing就发挥了自己的用途。
Another usage for Nothing is the return type for methods which never return normally. One example is method error in scala.sys, which always throws an exception.
Nothing也被用在当方法不正常返回的场合。比如sys.error("err")。它的源码是:
def error(message: String): Nothing = throw new RuntimeException(message)
这个方法不会返回Unit,因为它不是正常结束,是异常中断了。