The isNotEmpty
method of List
can be used to check if the List
contains at least one element.
fun <T> Collection<T>.isNotEmpty(): Boolean
This method doesn’t take any argument.
This method returns true
if the List
contains at least one element. Otherwise, false
will be returned.
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}
In the above code:
Line 3: We create an 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.