Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

How to use the isNullOrEmpty method of MutableList in Kotlin

Programming Bytes

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 list
  val nullList: MutableList<Any>? = null
  println("nullList is =>$nullList")
  println("nullList.isNullOrEmpty() => ${nullList.isNullOrEmpty()}") // true

  // create an empty list
  val emptyList= mutableListOf<Int>()
  println("\nemptyList is =>$emptyList")
  println("emptyList.isNullOrEmpty() => ${emptyList.isNullOrEmpty()}") // true

  // create an non-empty and not-null list
  val validList = mutableListOf(1)
  println("\nvalidList is =>$validList")
  println("validList.isNullOrEmpty() => ${validList.isNullOrEmpty()}") // false
}
Using isNullOrEmpty method to check if the list is null or empty

Explanation

  • Line 3: We create a variable nullList with type as MultableList and assign null as value.

  • Line 5: We call the isNullOrEmpty method of the nullList. The value of the nullList variable is null so True is returned.

  • Line 8: We create an empty MultableList (variable name nullList) by calling the multableListOf method without argument.

  • Line 10: We call the isNullOrEmpty method of the emptyList. The emptyList contains no elements so True is returned.

  • Line 13: We create a MultableList(variable name validList) by calling the multableListOf method with the 1 and 2 argument. The multableListOf method returns an MultableList object with [1,2] as elements.

  • Line 15: We call the isNullOrEmpty method of the validList. The validList contains two elements so False is returned.

RELATED TAGS

kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring