How to use – Option, None, Some in Scala

Scala handles or encourages developers to handle null values differently from what is typically followed in other languages like java. In java codes you typically check for null and proceed. Scala encourages developers to use the Option/Some/None pattern instead. This is an elegant way to handle the nulls. This means, if you want to pass null to a method you pass it as None instead of null. Yes, you need to modify the function to accept an Option. This is explained in below sections with examples.

The problem

You want to handle empty values in scala code or you want handle nulls and non null differently. This is a typical problem we can see every where in any code.

The pattern

You are expecting say a string as input to a function, instead of declaring the function to accept a string, you define it to accept Option[String]. What this means, the value can be a Some or None. Some indicates there is a non null value and None indicates , yes, nothing is there. This is core of this pattern.

Example

package com.stackrules

object OptionSomeNone extends  App{

  def Hello(text:Option[String]) = {
    text match {
      case Some(v) =>
        println("We have value "+v);
      case None => println("No value");
    }
  }
  Hello(Some("Hello"));
  Hello(None);
}

This code expects the user to pass a None to the function if there is nothing to be passed. This enables the function to handle the cases of empty and non empty values in more elegant manner. Okay, this handles the empty and non empty values , but what happens if i invoke the above function as Hello(null), in this case the function will break and you will get Exception in thread “main” scala.MatchError: null

To handle this you can add one more case condition as case null => println(“No value”);

This will handle all cases and won’t break even if the caller of the function breaks the contract and passes a null instead of None.

Return Option from a function

Let us now look at how an Option can be returned from a function using the Option/Some/None pattern.

def convertToInt(v:String):Option[Int] = {
    try {
       Some(Integer.parseInt(v));
     }catch {
      case e: Exception => None;
    }
  }
 println(convertToInt("2"));
 println(convertToInt(""));
 println(convertToInt(null));
//Output
Some(2)
None
None

The function has handled all cases well. It will never return a null even if the supplied value is null. Like wise we can ensure we don’t return a null.

Leave a Comment