Benoît
Benoît

Reputation: 1100

Why must MutableMap.keys returns a MutableSet?

The MutableMap.keys property is defined as : abstract val keys: MutableSet<K>

I understand that the content of keys will change as the underlying map will change, but how can the keys it-self be modifiable ? IE : I see no logic in calling map.keys.add(xxx)

Rq: I came into this problem while creating a proxy around a MutableMap. I have to temper the entries and keys content, but do not want to implement the remove/add/clear methods

Upvotes: 4

Views: 329

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170899

It corresponds to the Java Map#keySet() method which is documented as follows:

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

The bolded parts explain why it's represented as MutableSet in Kotlin; otherwise you couldn't port Java code using these capabilities.

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93882

The MutableSet returned by keys throws UnsupportedOperationException if you try to add something. It provides remove and filtering (retainAll) operations, which can simplify actions that don't need to consider the values, only the keys.

If you're already using a MutableMap, it makes sense that you should also be able to work with the keys directly in a mutable way.

Upvotes: 4

Related Questions