Can not extend HashMap in Kotlin


#1

I am trying to extend from HashMap in order to override the put Method and register some data.

I have the following class:

class SomeClassExtendingHashMap : HashMap<String, Object>() {

}

I receive the following compilation error:

SomeClassExtendingHashMap.kt: (6, 7): Inherited platform declarations clash: The following declarations have the same JVM signature (getOrDefault(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;):
    fun getOrDefault(key: Any!, defaultValue: Object!): Object!
    fun getOrDefault(key: String, defaultValue: Object): Object

Per my understand getOrDefault from Kotlin is conflicting with Map.getOrDefault.
Is there a better way to handle that?


#2

What Kotlin version do you use?
Your sample compiles on 1.1-M02 (try with http://try.kotlinlang.org/)


#3

This is not an answer for your particular question, but you may also consider another approach, using delegation:

class SomeClassExtendingHashMap(val underlying:HashMap<String, Any>) : MutableMap<String, Any> by underlying {
    override fun get(key: String): Any? {
        return underlying[key]
    }
}

#4

I just ran into the same issue when compiling with Gradle 3.2.1 and Kotlin 1.0.5-3. With Gradle 3.1 and the same version of Kotlin, the same code compiles just fine.

Is this a Gradle regression?


#5

I created this issue:

https://youtrack.jetbrains.com/issue/KT-15313