首页 > 其他 > 详细

Scala Nothing 从官方DOC翻译

时间:2015-12-04 22:29:56      阅读:242      评论:0      收藏:0      [点我收藏+]

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,因为它不是正常结束,是异常中断了。

Scala Nothing 从官方DOC翻译

原文:http://www.cnblogs.com/shuada/p/5020310.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!