There are 2 variations for the syntax of Map.getValue() extension function. They are:
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.
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.
In this example,
getValue
function on the map, providing an existing key ("key1"
)."key1"
is returned.fun main(args: Array<String>) {
val map = mapOf("key1" to "value1", "key2" to "value2")
val result = map.getValue("key1")
println(result)
}
value1
In this example,
getValue
function on the map, providing an existing key ("B"
)."B"
is returned.fun main(args: Array<String>) {
val map = mapOf("A" to 1, "B" to 2, "C" to 3)
val result = map.getValue("B")
println(result)
}
2
In this example,
getValue
function on the map, providing an existing key ("banana"
)."banana"
is returned.fun main(args: Array<String>) {
val map = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
val result = map.getValue("banana")
println(result)
}
6
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.