Scala list isEmpty() operation with examples

51 total views, 1 views today

Welcome to the Scala series. In this tutorial, you will learn about the Scala List isEmpty() operation with examples.

Scala isEmpty() allows checking if the list is empty.

Scala isEmpty() operation is applicable for all types of Scala collections

Scala isEmpty() returns a boolean value. It returns true if the list is empty else false.

isEmpty() Syntax

final def isEmpty: Boolean

Tests whether the list is empty.

Scala List isEmpty() examples

In this isEmpty() example, we have created a list and called isEmpty() method to check if the list is empty.

object IsEmptyTest {

  def main(args: Array[String]): Unit = {

    case class Person(var name: String, age: Int)

    //create a List
    var list = List(Person("Raj", 27), Person("John", 27), Person("Sri", 26), Person("Radha", 26), Person("Wick", 28))

    //Check isEmpty
    println(list.isEmpty)

  }
}

Output

false

Let us see another example of isEmpty() method.

object IsEmptyTest {

  def main(args: Array[String]): Unit = {

    //create List
    var list1 = List()

    //Check isEmpty
    println(list1.isEmpty)

  }
}

Output

true

What if the list is None? let us check an example to see what happens if we  call isEmpty()

object IsEmptyTest {

  def main(args: Array[String]): Unit = {

    //create List
    var list1 = None

    //Check isEmpty
    println(list1.isEmpty)

  }
}

Output

true

What if the list is Nil? let us check an example to see what happens if we call isEmpty()

object IsEmptyTest {

  def main(args: Array[String]): Unit = {

    //create List
    var list1 = Nil

    //Check isEmpty
    println(list1.isEmpty)

  }
}

Output

true

ReferencesScala isEmpty() operation

Would you like to learn more about Scala features, please check out Scala – a complete guide series. In this tutorial guide, you will find useful Scala functions that can be applied to the collection.

I hope you like this tutorial and you were able to understand the Scala list isEmpty() operation with examples.

Thanks for reading and please give us a thumb up and comment below.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.