The syntax of Map.withDefault() extension function is:
fun <K, V> Map<K, V>.withDefault( defaultValue: (key: K) -> V ): Map<K, V>
This withDefault() extension function of Map returns a wrapper of this read-only map, having the implicit default value provided with the specified function defaultValue.
In this example,
map1
containing key-value pairs "key1" to "value1"
and "key2" to "value2"
.withDefault
extension function with a default value function that returns "defaultValue"
."key3"
that is not present in the original map, returning the default value.fun main(args: Array<String>) {
val map1 = mapOf("key1" to "value1", "key2" to "value2");
val mapWithDefault = map1.withDefault { "defaultValue" };
println(mapWithDefault["key3"]);
}
defaultValue
In this example,
map2
containing key-value pairs "name" to "John Doe"
and "age" to "30"
.withDefault
extension function with a custom default value function that returns a string with the key name for unknown keys."gender"
that is not present in the original map, returning the custom default value.fun main(args: Array<String>) {
val map2 = mapOf("name" to "John Doe", "age" to "30");
val mapWithDefault = map2.withDefault { key -> "Unknown key: $key" };
println(mapWithDefault["gender"]);
}
Unknown key: gender
In this example,
map3
containing key-value pairs "city" to "New York"
and "country" to "USA"
.withDefault
extension function with a default value function that returns a string indicating the location was not found for the key."state"
that is not present in the original map, returning the default value indicating the location was not found.fun main(args: Array<String>) {
val map3 = mapOf("city" to "New York", "country" to "USA");
val mapWithDefault = map3.withDefault { key -> "Location not found for: $key" };
println(mapWithDefault["state"]);
}
Location not found for: state
In this Kotlin tutorial, we learned about withDefault() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.