我是斯卡拉的新手!
我的问题是,如果有包含成员的案例类
myItem:Option[String]
Run Code Online (Sandbox Code Playgroud)
当我构造类时,我需要将字符串内容包装在:
Option("some string")
Run Code Online (Sandbox Code Playgroud)
要么
Some("some string")
Run Code Online (Sandbox Code Playgroud)
有什么区别吗?
谢谢!
ser*_*jja 53
如果你看看Scala的来源,你会发现,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
Run Code Online (Sandbox Code Playgroud)
Pet*_*ter 11
Option(x) 基本上只是说 if (x != null) Some(x) else None
请参阅源代码的第25行:
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6905 次 |
| 最近记录: |