(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.
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.
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.
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>()
The Kotlin in Action book says the following about ArrayList
and HashMap
:
Kotlin sees them as if they inherited from the Kotlin’s
MutableList
andMutableSet
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With