Understanding Option Class in Scala

While programming in Java(earlier versions the Java 8), majority of us have come across a situation here we get NullPointerException. It happens because many times we write a code without checking all possibilities and method returns null value under certain conditions.So how to get rid of NullPointerException while writing a program?

Scala(even Java 8) solves this problem by one of its type Option. Option[T] is a kind of wrapper for none or one value of given type.

Option[T] return either,

  • Object of Some[T] in case value is present or
  • Object of None in case value is not available

In both of the cases it gives back an object by which there is no chance of getting NullPointerException in our code. In Scala APIs they have taken care of NullPointerException exception using Option class but if we want to understand how it works let’s take an example of Java,

Now where ever we use above method we need to make sure that we put a check for null because it is potentially possible to get NumberFormatException exception in getScore() method.

Rather putting extra check for exception Scala provides a way to return some value in form of Option which either have Some or None as a value.

Ignore exception handling part as of now. I’ll explain you in my post related to Exception Handling in Scala. Above method returns Option class so whatever variable would use it’s return value will definitely contain a value either Some or None so there is no need to put an extra check for Null values in Scala.

Even most of methods of the Scala collection classes also uses Option class as a return value. We’ll have more examples on Option in my upcoming posts.

Leave a Reply

Notify of