Kotlin Tutorials

Kotlin Map orEmpty()
Syntax & Examples

Syntax of Map.orEmpty()

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

fun <K, V> Map<K, V>?.orEmpty(): Map<K, V>

This orEmpty() extension function of Map returns the Map if its not null, or the empty Map otherwise.



✐ Examples

1 Handle null map

In this example,

  • We declare a nullable map named map1 and initialize it to null.
  • We then apply the orEmpty() function on map1.
  • As a result, an empty map is returned since map1 is null.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1: Map<String, Int>? = null
    val result = map1.orEmpty()
    println(result)
}

Output

{}

2 Handle non-null map

In this example,

  • We declare a nullable map named map2 and initialize it to a map containing key-value pairs.
  • We then apply the orEmpty() function on map2.
  • As a result, map2 is returned since it is not null.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2: Map<String, Int>? = mapOf("a" to 1, "b" to 2, "c" to 3)
    val result = map2.orEmpty()
    println(result)
}

Output

{a=1, b=2, c=3}

3 Handle empty map

In this example,

  • We declare a nullable map named map3 and initialize it to an empty map.
  • We then apply the orEmpty() function on map3.
  • As a result, map3 is returned since it is not null.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3: Map<String, Int>? = emptyMap()
    val result = map3.orEmpty()
    println(result)
}

Output

{}

Summary

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