Kotlin Tutorials

Kotlin Map withDefault()
Syntax & Examples

Syntax of Map.withDefault()

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.



✐ Examples

1 Map with default value

In this example,

  • We create a map named map1 containing key-value pairs "key1" to "value1" and "key2" to "value2".
  • We use the withDefault extension function with a default value function that returns "defaultValue".
  • The resulting map with default value is accessed with a key "key3" that is not present in the original map, returning the default value.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf("key1" to "value1", "key2" to "value2");
    val mapWithDefault = map1.withDefault { "defaultValue" };
    println(mapWithDefault["key3"]);
}

Output

defaultValue

2 Map with custom default value

In this example,

  • We create a map named map2 containing key-value pairs "name" to "John Doe" and "age" to "30".
  • We use the withDefault extension function with a custom default value function that returns a string with the key name for unknown keys.
  • The resulting map with custom default value is accessed with a key "gender" that is not present in the original map, returning the custom default value.
  • We print the result to standard output.

Kotlin Program

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"]);
}

Output

Unknown key: gender

3 Map with location not found default value

In this example,

  • We create a map named map3 containing key-value pairs "city" to "New York" and "country" to "USA".
  • We use the withDefault extension function with a default value function that returns a string indicating the location was not found for the key.
  • The resulting map with default value is accessed with a key "state" that is not present in the original map, returning the default value indicating the location was not found.
  • We print the result to standard output.

Kotlin Program

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"]);
}

Output

Location not found for: state

Summary

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.