2014-04-07 129 views

回答

44

如果你看看Scala's sources,你會發現,Option(x)只是評估x和非空輸入返回Some(x)Nonenull輸入。

我會使用Option(x)時,我不知道是否x可以null或沒有,Some(x)在100%肯定xnull

一個更需要考慮的是,當你想創建一個可選值,Some(x)產生更多的代碼,因爲你必須明確地指向值的類型:

val x: Option[String] = Some("asdasd") 
//val x = Option("asdasd") // this is the same and shorter 
9

Option(x)基本上只是說if (x != null) Some(x) else None

line 25 of the Source code

def apply[A](x: A): Option[A] = if (x == null) None else Some(x) 
相關問題