Why has Kotlins SortedMap no .forEachIndexed() function?

1.1k Views Asked by At

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)

2

There are 2 best solutions below

0
AlexT On BEST ANSWER

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.

0
Sweeper On

forEachIndexed is an extension function on all sorts of Arrays and also Iterable. SortedMap is unrelated to those types, so you can't call forEachIndexed on it.

However, SortedMap does have asIterable (inherited from Map), which converts it to an Iterable. After that, you can access forEachIndexed:

someSortedMap.asIterable().forEachIndex { index, entry ->
    // ...
}

However, the newer extension function onEachIndexed are declared on Maps. Unlike forEachIndexed, this also returns the map itself.