Kotlin Map getValue()
Syntax & Examples


Syntax of Map.getValue()

There are 2 variations for the syntax of Map.getValue() extension function. They are:

1.
operator fun <V, V1 : V> Map<in String, V>.getValue( thisRef: Any?, property: KProperty<*> ): V1

This extension function returns the value of the property for the given object from this read-only map.

2.
fun <K, V> Map<K, V>.getValue(key: K): V

This extension function returns the value for the given key or throws an exception if there is no such key in the map.



✐ Examples

1 Get value for an existing key

In this example,

  • We create a map with existing key-value pairs.
  • We use the getValue function on the map, providing an existing key ("key1").
  • The value associated with "key1" is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf("key1" to "value1", "key2" to "value2")
    val result = map.getValue("key1")
    println(result)
}

Output

value1

2 Get value for an existing key (numeric value)

In this example,

  • We create a map with existing key-value pairs.
  • We use the getValue function on the map, providing an existing key ("B").
  • The value associated with "B" is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf("A" to 1, "B" to 2, "C" to 3)
    val result = map.getValue("B")
    println(result)
}

Output

2

3 Get value for an existing key (numeric value)

In this example,

  • We create a map with existing key-value pairs.
  • We use the getValue function on the map, providing an existing key ("banana").
  • The value associated with "banana" is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
    val result = map.getValue("banana")
    println(result)
}

Output

6

Summary

In this Kotlin tutorial, we learned about getValue() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.