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.
In this example,
map1
and initialize it to null
.orEmpty()
function on map1
.map1
is null
.fun main(args: Array<String>) {
val map1: Map<String, Int>? = null
val result = map1.orEmpty()
println(result)
}
{}
In this example,
map2
and initialize it to a map containing key-value pairs.orEmpty()
function on map2
.map2
is returned since it is not null
.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)
}
{a=1, b=2, c=3}
In this example,
map3
and initialize it to an empty map.orEmpty()
function on map3
.map3
is returned since it is not null
.fun main(args: Array<String>) {
val map3: Map<String, Int>? = emptyMap()
val result = map3.orEmpty()
println(result)
}
{}
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.