Open In App

How to Check for Null in a Single Statement in Scala?

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Scala, null is a Special type value that represents the absence of a value or a reference or the unavailability of a value for a variable. It is important to handle null values in programming otherwise it can lead to NullPointerException. In this article, we are going to see different examples that show how to handle null values efficiently in Scala.

Using if Statement

In this example, we are going to see how to handle null values using an if statement by checking if a string is null or not in Scala.

Scala
object Main {
  def main(args: Array[String]): Unit = {
    val nullableString: String = null;
    val result = if (nullableString != null) nullableString else "Null String";
    print(result);
  }
}

Output:

Null String

Using Option with getOrElse

In this example we are going to see how to handle null values using Option with getOrElse by checking if a string is null or not in Scala.

  1. Option: Option is a container type in Scala that represents an optional value: a value that may be present or not.
  2. getOrElse: It allows you to retrieve the value from a statement or a varriable if it exists, or provide a default value if the Option is None .
Scala
object Main {
    def main(args: Array[String]) {
        val nullableString: String = null;
        val result = Option(nullableString).getOrElse("Null String");
        print(result);
    }
}

Output:

Null String

Using fold on Option

In this example we are going to see how to handle null values using fold on Option by checking if a string is null or not in Scala.

Scala
object Main {
    def main(args: Array[String]) {
        val nullableString: String = null;
        val result = Option(nullableString).fold("Null String")(identity);
        print(result);
    }
}

Output:

Null String

Using null Coalescing via Option

In this example we are going to see how to handle null values using null Coalescing via Option by checking if a string is null or not in Scala.

Scala
object Main {
    def main(args: Array[String]) {
        val nullableString: String = null;
        val result = Option(nullableString).orNull;
        print(result);

    }
}

Output:

null

Using getOrElse Directly

In this example we are going to see how to handle null values using ngetorElse directly by checking if a string is null or not in Scala.

Scala
object Main {
    def main(args: Array[String]) {
        val result = Option(null).getOrElse("Null String");
        print(result);
    }
}

Output:

Null String


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads