MutableSet viewa for MutableMap make no sense

I am trying to write a custom TreeMap implementation in Kotlin multiplatform. Everything works fine until I encountered the keys(), values() and entries() methods. These must return views that reflect changes in the underlying map. Similar to Javas TreeMap, I want to implement them as lazy initialized anonymous inner classes like so:

override val keys: MutableSet<K> by lazy {
        object : MutableSet<K> {
               ...
            override fun add(element: K): Boolean {
                TODO("This makes no sense?! WHat value should be added to map?")
            }
        }

However, unlike Java, Kotlins MutableMap interface requires these Sets to be MUTABLE as well, with changes made to the views changing the underlying map itself. This is a problem, since it is unclear how MutableSet’s add() which only specifies a key should modify the map (which needs both a key and a value).
This tension needs to be resolved somehow. For values, this problem is even worse for trying to add or remove values because a value might have multiple keys. I think these views really must be read only (unmutable) even for the MutableMap to not break the Map contract. Is the MutableMap (kotlin.collections.MutableMap) “fixed”? Is this something open to discussion? If not, how are these cases supposed to be handled?

You can take a look at the complete implementation here Daniel63656/SortedCollections: Implementation of Sorted Set and Map in Kotlin (github.com).
Only these view methods are missing.

Edit: I noticed that Java throws UnsupportedOperationException in these cases.

1 Like

Yeah I would just do the same in your implementation, tbh. You’re right that it makes no sense for these Views to be modified. I’m guessing it uses MutableSet for compatibility with Java, perhaps.