Joshua
Joshua

Reputation: 77

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.

Upvotes: 5

Views: 1303

Answers (1)

zsmb13
zsmb13

Reputation: 89578

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.

Upvotes: 5

Related Questions