This is a quick post showing the difference between Some and Option. When I first started using Scala, I did not understand the difference between ‘Some’ and ‘Option’. Though subtle, the difference is an important one and helps decide which is to use when.
Handling of null values
The main and the most important difference between the two is their way of handling null values. While null values equate to None when used with Option, with Some null becomes a value itself as illustrated by the example below –
Some –
scala> val s1: Some[String] = Some("abc")
s1: Some[String] = Some(abc)
scala> val s2: Some[String] = Some(null)
s2: Some[String] = Some(null)
scala> s1.isDefined
res5: Boolean = true
scala> s2.isDefined
res6: Boolean = true
In the example above, even though s2 was provided a null value, the isDefined results in true.
Option –
scala> val o1: Option[String] = Option("abc")
o1: Option[String] = Some(abc)
scala> val o2: Option[String] = Option(null)
o2: Option[String] = None
scala> o1.isDefined
res3: Boolean = true
scala> o2.isDefined
res4: Boolean = false
With Option however, o2 becomes a None and isDefined results in false. This is particularly useful when we want to check if a value was really defined without having to equate it to null.
As can be seen here, Option really is –
def apply[A](x: A): Option[A] = if (x == null) None else Some(x)