Scala中的 Nothing,Null,None,Nil 的区别

scala的继承层级


Scala中的 Nothing,Null,None,Nil 的区别_第1张图片

Null 和 null


  • Null is a type
    final trait Null extends AnyRef
  • null is a value
    the only one instance of Null

Null是所有AnyRef的子类,在scala的类型系统中,AnyRef是Any的子类,同时Any子类的还有AnyVal。对应java值类型的所有类型都是AnyVal的子类。所以Null可以赋值给所有的引用类型(AnyRef),不能赋值给值类型,这个java的语义是相同的。 null是Null的唯一对象。

def tryit(thing: Null): Unit = { println("That worked!"); }
tryit: (null) Unit
 
tryit("hey")
<console>:6: error: type mismatch;
found : java.lang.String("hey")
required: Null
tryit("hey")
    ^
 
val someRef: String = null  // val someRef = null       is ok
someRef: String = null
scala> tryit(someRef)
<console>:7: error: type mismatch;
found : String
required: Null
tryit(someRef)
    ^
 
scala> tryit(null)
That worked!
 
scala> val nullRef: Null = null
nullRef: Null = null
 
scala> tryit(nullRef)
That worked!

Nothing


  • final trait Nothing extends Any
  • Nothing is a subtype of everything
  • There is no instance of Nothing

Any collection of Nothing must necessarily be empty
Any methods with return of Nothing never return normally, such as one method always throws
exception

Nothing是所有类型的子类,它没有对象,但是可以定义类型,如果一个类型抛出异常,那这个返回值类型就是Nothing

任何Nothing 的集合都必须是空的
任何返回Nothing的方法都不会正常返回,例如一个方法总是抛出异常



//场景 在客户表中如果没有录入客户年龄这个字段,可以用 Nothing
 
//A Nothing is a String
scala> val emptyStringList: List[String] = List[Nothing]()
emptyStringList: List[String] = List()
 
//A Nothing is an Int
scala> val emptyIntList: List[Int] = List[Nothing]()
emptyIntList: List[Int] = List()
 
//A String is not a Nothing
scala> val emptyStringList: List[String] = List[Nothing]("abc")
<console>:4: error: type mismatch;
found : java.lang.String("abc")
required: Nothing
    val emptyStringList: List[String] = List[Nothing]("abc")
 
def process(): Unit = {}
def process(): Null = { null }
def process(): Nothing = {}

Nil 和 None


  • case object Nil extends List[Nothing]
  • object None extends Option[Nothing]

Nil是一个空的List,extends List[Nothing],所有Nil是所有List[T]的子类。
None是一个object,是 Option[Nothing] 的子类

scala> Nil
res4: Nil.type = List()
scala> Nil.length
res5: Int = 0
scala> Nil + "ABC"
res6: List[java.lang.String] = List(ABC)

-----------------------------------------
def getAStringMaybe(num: Int): Option[String] = {
    if ( num >= 0 ) Some("A positive number!")
    else None
}
 
def printResult(num: Int) = {
    getAStringMaybe(num) match {
    case Some(str) => println(str)
    case None => println("No string!")
    }
}
printResult(100)
A positive number!
 
printResult(-50)
No string!

你可能感兴趣的:(Scala中的 Nothing,Null,None,Nil 的区别)