The syntax of Map.getOrElse() extension function is:
fun <K, V> Map<K, V>.getOrElse( key: K, defaultValue: () -> V ): V
This getOrElse() extension function of Map returns the value for the given key if the value is present and not null. Otherwise, returns the result of the defaultValue function.
In this example,
map1
containing key-value pairs.getOrElse()
function on map1
with key 'b'
to retrieve its corresponding value.0
is returned.'b'
is printed to standard output.fun main(args: Array<String>) {
val map1 = mapOf("a" to 1, "b" to 2, "c" to 3)
val value1 = map1.getOrElse("b") { 0 }
println(value1)
}
2
In this example,
map2
containing key-value pairs.getOrElse()
function on map2
with key 2
to retrieve its corresponding value.'x'
is returned.2
is printed to standard output.fun main(args: Array<String>) {
val map2 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val value2 = map2.getOrElse(2) { 'x' }
println(value2)
}
b
In this example,
map3
containing key-value pairs.getOrElse()
function on map3
with key 4
to retrieve its corresponding value.'default'
is returned.4
is printed to standard output.fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry")
val value3 = map3.getOrElse(4) { "default" }
println(value3)
}
default
In this Kotlin tutorial, we learned about getOrElse() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.