I am new to scala !
My question is, if there is case class that contains a member
myItem:Option[String]
When i construct the class,
If you look into Scala's sources you'll notice that Option(x)
just evaluates x
and returns Some(x)
on not-null input, and None
on null
input.
I'd use Option(x)
when I'm not sure whether x
can be null
or not, and Some(x)
when 100% sure x
is not null
.
One more thing to consider is when you want to create an optional value, Some(x)
produces more code because you have to explicitly point the value's type:
val x: Option[String] = Some("asdasd")
//val x = Option("asdasd") // this is the same and shorter
Option(x)
is basically just saying if (x != null) Some(x) else None
See line 25 of the Source code:
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)