nil :作为 List[T]的初始化,表示一个空数组 官方文档解释
null :表示一个空对象,是Null唯一的实例
Null :不用怎么管这个,基本不会用到。
Nothing and Null
Nothing is a subtype of all types, also called the bottom type. There is no value that has type Nothing. A common use is to signal non-termination such as a thrown exception, program exit, or an infinite loop (i.e., it is the type of an expression which does not evaluate to a value, or a method that does not return normally).
Null is a subtype of all reference types (i.e. any subtype of AnyRef). It has a single value identified by the keyword literal null. Null is provided mostly for interoperability with other JVM languages and should almost never be used in Scala code. We’ll cover alternatives to null later in the tour.
None
None是一个object,是Option的子类型,定义如下
case object None extends Option[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}
scala推荐在可能返回空的方法使用Option[X]作为返回类型。如果有值就返回Some[x](Some也是Option的子类),否则返回None,例如
def get(key: A): Option[B] = {
if (contains(key))
Some(getValue(key))
else
None
}
获得Option后,可以使用get获得包含的值,或者使用getOrElse获得默认值如果isEmpty为true。
这个None还没能理解
本文介绍了Scala中Nil、Null与None的区别及其应用场景。Nil用于List[T]的初始化,表示空数组;Null作为所有引用类型的子类型,主要用于与其他JVM语言的互操作;而None则是一个Option子类型,用于表示可能返回空的方法。
422

被折叠的 条评论
为什么被折叠?



