Kotlin Tutorials

Kotlin Map isNullOrEmpty()
Syntax & Examples

Syntax of Map.isNullOrEmpty()

The syntax of Map.isNullOrEmpty() extension function is:

fun <K, V> Map<out K, V>?.isNullOrEmpty(): Boolean

This isNullOrEmpty() extension function of Map returns true if this nullable map is either null or empty.



✐ Examples

1 Check if a non-empty map is null or empty

In this example,

  • We create a non-empty map named map1.
  • We use the isNullOrEmpty function on map1.
  • Since map1 is non-empty, the function returns false.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf("key1" to "value1", "key2" to "value2")
    val result1 = map1.isNullOrEmpty()
    println(result1)
}

Output

false

2 Check if an empty map is null or empty

In this example,

  • We create an empty map named map2.
  • We use the isNullOrEmpty function on map2.
  • Since map2 is empty, the function returns true.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = emptyMap<String, Int>()
    val result2 = map2.isNullOrEmpty()
    println(result2)
}

Output

true

3 Check if a nullable map is null or empty

In this example,

  • We declare a nullable map map3 and assign it a value of null.
  • We use the isNullOrEmpty function on map3.
  • Since map3 is null, the function returns true.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3: Map<String, String>? = null
    val result3 = map3.isNullOrEmpty()
    println(result3)
}

Output

true

Summary

In this Kotlin tutorial, we learned about isNullOrEmpty() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.