Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 520
m.reiter Avatar asked Sep 01 '26 02:09

m.reiter


2 Answers

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
}
like image 82
AlexT Avatar answered Sep 04 '26 00:09

AlexT


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.

like image 30
Sweeper Avatar answered Sep 04 '26 00:09

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!