I am not able to understand the point of Option[T]
class in Scala. I mean, I am not able to see any advanages of None
over null
.
For example, consider the code:
object Main{
class Person(name: String, var age: int){
def display = println(name+" "+age)
}
def getPerson1: Person = {
// returns a Person instance or null
}
def getPerson2: Option[Person] = {
// returns either Some[Person] or None
}
def main(argv: Array[String]): Unit = {
val p = getPerson1
if (p!=null) p.display
getPerson2 match{
case Some(person) => person.display
case None => /* Do nothing */
}
}
}
Now suppose, the method getPerson1
returns null
, then the call made to display
on first line of main
is bound to fail with NPE
. Similarly if getPerson2
returns None
, the display
call will again fail with some similar error.
If so, then why does Scala complicate things by introducing a new value wrapper (Option[T]
) instead of following a simple approach used in Java?
UPDATE:
I have edited my code as per @Mitch's suggestion. I am still not able to see any particular advantage of Option[T]
. I have to test for the exceptional null
or None
in both cases. :(
If I have understood correctly from @Michael's reply, is the only advantage of Option[T]
is that it explicitly tells the programmer that this method could return None? Is this the only reason behind this design choice?
get
, and you'll get it. :-) – Cozartforeach
,map
andflatMap
are just niceties. – VirtuositygetPerson2.foreach(p => p.display)
is simpler than both code examples given. Pattern matching is necessary when you want to do something in theNone
case. – Horotelic