简体   繁体   中英

How does HashMap implement the MutableMap interface in Kotlin?

(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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM