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 integerval emptyList:List<Int> = listOf()println("emptyList : ${emptyList}")println("emptyList.isNotEmpty() : ${emptyList.isNotEmpty()}") // false//create another list with elementsval 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
with the nameempty list List with no elements in it emptyListusing thelistOfmethod. -
Line 5: We use the
isNotEmptymethod to check if theemptyListcontains at least one element. But theemptyListcontains no elements, sofalseis returned. -
Line 8: We create a list with the name
validListusing thelistOfmethod. ThevalidListhas three elements,1,2,3. -
Line 10: We use the
isNotEmptymethod to check if thevalidListcontains at least one element. ThevalidListcontains three elements, sotrueis returned.