Scala Check if String Is Null or Empty

1. Introduction

In Scala programming, checking whether a string is null or empty is a fundamental and frequently encountered operation. This is especially important for validation purposes and to ensure the robustness of the code against null reference errors. Scala offers concise ways to perform this check. This blog post will demonstrate how to check if a string in Scala is null or empty.

2. Program Steps

1. Define strings that may be null or empty.

2. Write a function or use a built-in method to check if the strings are null or empty.

3. Print the results to verify the checks.

4. Execute the code to observe the behavior of the check.

3. Code Program

object StringNullOrEmptyCheckDemo extends App {
  val nonEmptyString = "Hello Scala"
  val emptyString = ""
  val nullString: String = null

  // Function to check if a string is null or empty
  def isNullOrEmpty(str: String): Boolean = str == null || str.isEmpty

  // Checking the strings
  println(s"Is 'nonEmptyString' null or empty? ${isNullOrEmpty(nonEmptyString)}")
  println(s"Is 'emptyString' null or empty? ${isNullOrEmpty(emptyString)}")
  println(s"Is 'nullString' null or empty? ${isNullOrEmpty(nullString)}")
}

Output:

Is 'nonEmptyString' null or empty? false
Is 'emptyString' null or empty? true
Is 'nullString' null or empty? true

Explanation:

1. Three different strings are defined: a non-empty string, an empty string, and a null string.

2. The function isNullOrEmpty checks whether a string is null or empty. It uses the logical OR (||) operator to return true if either condition is met.

3. The function is applied to each string, and the results are printed.

4. The output indicates that only the non-empty string passes the check, while both the empty and null strings are identified as either null or empty.


Comments