Q:

Scala program to check a List collection is empty or not

belongs to collection: Scala List Programs

0

Here, we will create two lists of integers using List collection. Then we will check a List collection is empty or not using the isEmpty property and print the appropriate message on the console screen.

The List collection is used to store ordered elements. It extends the LinearSeq trait and is used for the immutable linked list.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to check a List collection is empty or not is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to check a List collection
// is empty or not

import scala.collection.immutable._

object Sample {
  // Main method
  def main(args: Array[String]) {
    var intList1 = List();
    var intList2 = List(8, 5, 3, 2, 4);

    if (intList1.isEmpty)
      println("intList1 is empty");
    else
      println("intList1 is not empty");

    if (intList2.isEmpty)
      println("intList2 is empty");
    else
      println("intList2 is not empty");
  }
}

Output:

intList1 is empty
intList2 is not empty

Explanation:

In the above program, we used an object-oriented approach to create the program. Here we imported Collection classes using below statement,

import scala.collection.immutable._

Here, we also created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created two lists intList1intList2 using List collection. Then we used the isEmpty property of the List collection and printed the appropriate message on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to demonstrate the List.fill() metho... >>
<< Scala program to print the items of List collectio...