Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does HashMap implement the MutableMap interface in Kotlin?

Tags:

(Note: There is a potential spoiler for one of the Kotlin Koans below.)

Given a higher order function that takes a function literal like this:

fun <K, V> buildMap(build: MutableMap<K, V>.() -> Unit): Map<K, V> {
    // How does java.util.HashMap satisfy the MutableMap interface?
    // Does Kotlin support ducktyping?
    val map = HashMap<K, V>()
    map.build()
    return map
}

How is it that java.util.HashMap satisfies the MutableMap interface that build is targeted against? Does Kotlin support some sort of ducktyping or is this a special-case in the Kotlin language just for certain classes that are part of the JDK?

I looked at the Kotlin documentation on interfaces and searched a bit but couldn't find anything that seemed to explain this.

like image 339
Joshua Avatar asked Mar 04 '17 16:03

Joshua


People also ask

How does HashMap work in Kotlin?

Kotlin HashMap class implements the MutableMap interface using Hash table. It store the data in the form of key and value pair. It is represented as HashMap<key, value> or HashMap<K, V>. The implementation of HashMap class does not make guarantees about the order of data of key, value and entries of collections.

What is MutableMap in Kotlin?

Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.

How do you get the Kotlin MutableMap value?

The getValue() function used to returns corresponding value of specified key of the MutableMap or it throws an exception if no key found in map. For example: fun main(args: Array<String>) { val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()


1 Answers

The Kotlin in Action book says the following about ArrayList and HashMap:

Kotlin sees them as if they inherited from the Kotlin’s MutableList and MutableSet interfaces, respectively.

So basically yes, as you've proposed, it is a special case for these collections that's implemented somehow in the Kotlin compiler. Unfortunately, this is all the detail they provide, so if you want to know more, you probably have to dive into the source of the compiler.

I suppose the main takeaway is that this is not a language feature that you could use yourself.

like image 141
zsmb13 Avatar answered Sep 23 '22 09:09

zsmb13