how to override HashMap#set ? ```class JsonObject ...
# announcements
t
how to override HashMap#set ?
Copy code
class JsonObject : HashMap<String,Any?>() {
    // <https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order/38218582#38218582>
    // ES2015 require keep insertion order
    private val list = ArrayList<String>()

    // ERROR: set override nothing
     operator override fun set(key: String, value: Any?) {
        super.set(key,value)
        if(!list.contains(key)) list.add(key)
    }
s
set
is not a method of Map or HashMap, it’s an extension method from stdlib. You should override
put
t
oh, thanks
d
What's the use-case for extending
HashMap
btw?
d
LinkedHashMap
preserves insertion order. So you can just do
class JsonObject : MutableMap<String, Any?>(linkedHashMapOf())
.
💯 2
t
hm
a
But should your JsonObject be a Map , or should it use a Map ? (Composition over Inheritance)
☝️ 1
s
Just making a compiling version of what Dominic said:
Copy code
class JsonObject : MutableMap<String, Any?> by LinkedHashMap()
But you should consider Andre’s question.
d
Oops, that's what I meant. I should get some sleep.
😄 2
s
And one last thing to consider, depending on your use-case. If all you wanted was a Map that guarantees order, maybe just use LinkedHashMap directly without extending it? Or maybe just a typealias for convenience?
Copy code
typealias JsonObject = LinkedHashMap<String, Any?>
t
ES2015 has more rules to object enumeration. I have to override some methods.