Scala Option, Some, None – Exception and Null handling

In the previous post, we discussed the Try, Success, Failure exception handling method. Now, in this post, we will discuss the use of Scala’s Option, Some, None pattern and its usage. Scala is a high-level programming language combining object-oriented and functional programming in one place. It is a very powerful programming language that can be used to create very complex applications. Apache Spark and Apache Kafka are also written in Scala.

We can handle the null exception in multiple ways in Scala. However, Option, Some, None is a more clear way of null handling in Scala. Using the Option Some None pattern, we can easily write the exception and null handling code blocks.

Suppose, we want to divide a given number by another number. However, if the second number will be 0 then it will raise an arithmetic (Divide by zero) exception. To avoid this, we can wrap our code inside Option Some and None blocks.

Scala Option, Some, None – Example

This is the sample code we can use to handle this exception.

package com.sample.learning

object demoOptionSomeNone extends App {
  def divideFirstBySecond(firstNumber: Int, secondNumber: Int): Option[Int] = {
    secondNumber match {
      case 0 => None
      case _ => Some(firstNumber / secondNumber)
    }
  }

  //Execute with non zero values for first and second numbers
  println("*************************************************************")
  println("Executing with params: firstNumber = 10, secondNumber = 2")
  println(divideFirstBySecond(10, 2))
  println("*************************************************************")
  println()

  //Divide the first number by zero
  println("*************************************************************")
  println("Executing with params: firstNumber = 10, secondNumber = 0")
  println(divideFirstBySecond(10, 0))
  println("*************************************************************")
  println()
}

Output:

Sample code output
Sample code output

Above, we can see that we have used Option[Int] as the return type instead of the Int value. This way, firstly, we have checked if the second number is zero, then we have returned the None[Int]. However, if the second number is a non-zero number, then the Some[Int] value (an outcome of the first number divided by the second number) is returned. This is how we have efficiently managed the run-time exception that will occur if the given second given number is zero. Also, if this return is value is being used somewhere down the stream in the application, we can avoid the null exception also.

Thanks for the reading. Please share your inputs in the comment section.

Rate This
[Total: 1 Average: 5]

Leave a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.