So in Scala Some
and None
are the two sub-classes of Option
.
To get an instance of Some
, you can do both Some(x)
or Option(x)
scala> val x = "Foo"
x: String = Foo
scala> Some(x)
res0: Some[String] = Some(Foo)
scala> Option(x)
res1: Option[String] = Some(Foo)
So it looks like there's not much difference. But of course if x is null, then they behave differently.
scala> val x:String = null
x: String = null
scala> Some(x)
res0: Some[String] = Some(null)
scala> Option(x)
res1: Option[String] = None
So it looks like, unless you want to preserve the null (for whatever reason), Option(x)
is always preferable, because it's safer.
Even with literals, while we know for sure that Some("foo")
cannot yield null, if later the string is extracted to a variable, you have to change it to Option
to stay safe.
My question: Other than preserving null, is there any reason to use Some(x)
?