Home > Net >  How does Kotlin retrieve map values internally with its get function
How does Kotlin retrieve map values internally with its get function

Time:12-06

In Kotlin you create a map like this:

val items = mapOf("a" to 1, "b" to 2)

and retrieve a value like this:

val item = items["a"]

The bracket will call the get function. Looking at Kotlin's the source code for Maps, all that I see for the get function is this:

public operator fun get(key: K): V?

I couldn't find any implementation of get, so it's not clear how Kotlin internally finds a map item.

CodePudding user response:

Depending on how you create the Kotlin map, different implementation may be created. But in the concrete case of mapOf("a" to 1, "b" to 2) a kotlin.collections.LinkedHashMap will be created. LinkedHashMaps implementation depends on the target platform. More information can be found here: What does a LinkedHashMap create in Kotlin?. If the target platform is JVM then the underlying implementation if java.util.HashMap and it's get function.

CodePudding user response:

The operator [] is implemented as get on the various Map implementations, see for example default map here and empty map here.

  • Related