我是scala的新手!Option(value)和Some(value)之間的區別
我的問題是,如果有案例類包含一個成員
myItem:Option[String]
當我構建類,我需要包裝的字符串內容:
Option("some string")
OR
Some("some string")
有什麼區別嗎?
謝謝!
我是scala的新手!Option(value)和Some(value)之間的區別
我的問題是,如果有案例類包含一個成員
myItem:Option[String]
當我構建類,我需要包裝的字符串內容:
Option("some string")
OR
Some("some string")
有什麼區別嗎?
謝謝!
如果你看看Scala's sources,你會發現,Option(x)
只是評估x
和非空輸入返回Some(x)
和None
上null
輸入。
我會使用Option(x)
時,我不知道是否x
可以null
或沒有,Some(x)
在100%肯定x
不null
。
一個更需要考慮的是,當你想創建一個可選值,Some(x)
產生更多的代碼,因爲你必須明確地指向值的類型:
val x: Option[String] = Some("asdasd")
//val x = Option("asdasd") // this is the same and shorter
Option(x)
基本上只是說if (x != null) Some(x) else None
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)