How to use if Statement In Scala

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

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

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.

Table of Content

  • Using if Statement
  • Using Option with getOrElse
  • Using fold on Option
  • Using null Coalescing via Option
  • Using getOrElse Directly

Similar Reads

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....

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....

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....

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....

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....