How to use the isNotEmpty method of List in Kotlin

Overview

The isNotEmpty method of List can be used to check if the List contains at least one element.

Syntax

fun <T> Collection<T>.isNotEmpty(): Boolean

Parameters

This method doesn’t take any argument.

Return value

This method returns true if the List contains at least one element. Otherwise, false will be returned.

Code

The below code demonstrates how to use the isNotEmpty method in Kotlin:

fun main() {
// create a empty List of integer
val emptyList:List<Int> = listOf()
println("emptyList : ${emptyList}")
println("emptyList.isNotEmpty() : ${emptyList.isNotEmpty()}") // false
//create another list with elements
val validList:List<Int> = listOf(1,2,3)
println("\nvalidList : ${validList}")
println("validList.isNotEmpty() : ${validList.isNotEmpty()}") // true
}

Explanation

In the above code:

  • Line 3: We create an empty listList with no elements in it with the name emptyList using the listOf method.

  • Line 5: We use the isNotEmpty method to check if the emptyList contains at least one element. But the emptyList contains no elements, so false is returned.

  • Line 8: We create a list with the name validList using the listOf method. The validList has three elements, 1,2,3.

  • Line 10: We use the isNotEmpty method to check if the validList contains at least one element. The validList contains three elements, so true is returned.

Free Resources