Kotlin Map getOrElse()
Syntax & Examples
Syntax of Map.getOrElse()
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.
✐ Examples
1 Get value for key 'b'
In this example,
- We create a map named
map1
containing key-value pairs. - We use the
getOrElse()
function onmap1
with key'b'
to retrieve its corresponding value. - If the key is present, the corresponding value is returned; otherwise, the default value
0
is returned. - The value for key
'b'
is printed to standard output.
Kotlin Program
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)
}
Output
2
2 Get value for key 2
In this example,
- We create a map named
map2
containing key-value pairs. - We use the
getOrElse()
function onmap2
with key2
to retrieve its corresponding value. - If the key is present, the corresponding value is returned; otherwise, the default value
'x'
is returned. - The value for key
2
is printed to standard output.
Kotlin Program
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)
}
Output
b
3 Get value for key 4
In this example,
- We create a map named
map3
containing key-value pairs. - We use the
getOrElse()
function onmap3
with key4
to retrieve its corresponding value. - If the key is present, the corresponding value is returned; otherwise, the default value
'default'
is returned. - The value for key
4
is printed to standard output.
Kotlin Program
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)
}
Output
default
Summary
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.