Scala Check if List Is Null or Empty

1. Introduction

In Scala, checking if a list is null or empty is a common operation, especially when dealing with data that may not be initialized or could be empty. This is crucial in avoiding null pointer exceptions and in making code more robust and error-free. This blog post will demonstrate how to check if a list in Scala is null or empty.

2. Program Steps

1. Create a scenario with lists that might be null or empty.

2. Use a combination of null-check and isEmpty method to determine if a list is null or empty.

3. Print the results for each list to verify the check.

4. Execute the code to observe the outcome.

3. Code Program

object ListNullOrEmptyCheckDemo extends App {
  val nonEmptyList: List[Int] = List(1, 2, 3)
  val emptyList: List[Int] = List()
  val nullList: List[Int] = null

  // Function to check if a list is null or empty
  def isNullOrEmpty(list: List[Int]): Boolean = list == null || list.isEmpty

  // Checking the lists
  println(s"Is nonEmptyList null or empty? ${isNullOrEmpty(nonEmptyList)}")
  println(s"Is emptyList null or empty? ${isNullOrEmpty(emptyList)}")
  println(s"Is nullList null or empty? ${isNullOrEmpty(nullList)}")
}

Output:

Is nonEmptyList null or empty? false
Is emptyList null or empty? true
Is nullList null or empty? true

Explanation:

1. Three lists are defined: nonEmptyList with elements, emptyList which is empty, and nullList which is null.

2. The function isNullOrEmpty checks if a list is either null or empty using the logical OR (||) operator. It first checks if the list is null and then if it's empty.

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

4. The output clearly indicates that nonEmptyList is neither null nor empty, while both emptyList and nullList are considered empty according to the function.


Comments