选项(值)与某些(值)之间的差异

时间:2014-04-07 09:37:44

标签: scala

我是scala的新手!

我的问题是,如果有包含成员的案例类

myItem:Option[String]

当我构造类时,我需要将字符串内容包装在:

Option("some string")

OR

Some("some string")

有什么不同吗?

谢谢!

2 个答案:

答案 0 :(得分:52)

如果您查看Scala's sources,您会注意到Option(x)仅评估x并在非空输入上返回Some(x)Nonenull输入。

当我不确定Option(x)是否x时,我会使用null,而{100}肯定Some(x) x null 1}}不是Some(x)

还需要考虑的另一件事是,当您想要创建可选值时,val x: Option[String] = Some("asdasd") //val x = Option("asdasd") // this is the same and shorter 会生成更多代码,因为您必须明确指出值的类型:

{{1}}

答案 1 :(得分:11)

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)