dictionarykotlinsortedmap

Why has Kotlins SortedMap no .forEachIndexed() function?


Kotlins SortedMap is "a map that further provides a total ordering on its keys."

As a result, it should be indexable. However, this extension doesn't exist

`sortedMap.forEachIndexed()`

Why not? Am i overlooking something? Is it performance reasons? Didn't anyone bother?

(Yes, i know, i could use a List<Pair<Key, Value>>, but that's doesn't feel like the "intuitive" structure for my usecase, a map fits much better)


Solution

  • Most of the things that have a forEachIndexed get it either from Iterable or have it as an extension function. Map does not, but one of its properties, the entries, is actually a Set, which does have forEachIndexed because it inherits from Collection (which inherits from Iterable).

    That means that you can do something like this:

    map.entries.forEachIndexed { index, (key, value) ->
            //do stuff
    }
    

    The reason I've added this to the already existing asIterable().forEachIndex answer, is because asIterable() creates a new object.


    Side note, you do not have to destructure the entry if you do not want to, you can use it directly.

    map.entries.forEachIndexed { index, entry ->
            //do stuff with entry.key and entry.value
    }