How to use the isNullOrEmpty method of MutableList in Kotlin
Overview
The isNullOrEmpty method returns True if the MutableList is either null or empty.
Syntax
fun <T> Collection<T>?.isNullOrEmpty(): Boolean
Parameter
This method doesn’t take any argument.
Return value
This method returns a Boolean value. Returns True if the MutableList is null or empty. Otherwise, False is returned.
Code
The below code demonstrates how to use the isNullOrEmpty method:
fun main() {// create a null listval nullList: MutableList<Any>? = nullprintln("nullList is =>$nullList")println("nullList.isNullOrEmpty() => ${nullList.isNullOrEmpty()}") // true// create an empty listval emptyList= mutableListOf<Int>()println("\nemptyList is =>$emptyList")println("emptyList.isNullOrEmpty() => ${emptyList.isNullOrEmpty()}") // true// create an non-empty and not-null listval validList = mutableListOf(1)println("\nvalidList is =>$validList")println("validList.isNullOrEmpty() => ${validList.isNullOrEmpty()}") // false}
Explanation
-
Line 3: We create a variable
nullListwith type asMultableListand assignnullas value. -
Line 5: We call the
isNullOrEmptymethod of thenullList. The value of thenullListvariable isnullsoTrueis returned. -
Line 8: We create an empty
MultableList(variable namenullList) by calling themultableListOfmethod without argument. -
Line 10: We call the
isNullOrEmptymethod of theemptyList. TheemptyListcontains no elements soTrueis returned. -
Line 13: We create a
MultableList(variable namevalidList) by calling themultableListOfmethod with the1and2argument. ThemultableListOfmethod returns anMultableListobject with[1,2]as elements. -
Line 15: We call the
isNullOrEmptymethod of thevalidList. ThevalidListcontains two elements soFalseis returned.