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

scala的继承层级


Alt

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!
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值