ilansch
ilansch

Reputation: 4878

Difference between Option(value) and Some(value)

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, i need to wrap the string content in:

Option("some string")

OR

Some("some string")

Is there any difference ?

Thanks!

Upvotes: 37

Views: 9228

Answers (2)

user908853
user908853

Reputation:

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)

Upvotes: 16

serejja
serejja

Reputation: 23871

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

Upvotes: 62

Related Questions