I have list e.g. 1, 2, 3
. I want to map each value to * 2
, i.e. (1 to 2, 2 to 4, 3 to 6)
. Is there any stdlib function which can do this without explicitly restating the key?
I’d be looking to write something like list.whatGoesHere {it * 2}
.
I have list e.g. 1, 2, 3
. I want to map each value to * 2
, i.e. (1 to 2, 2 to 4, 3 to 6)
. Is there any stdlib function which can do this without explicitly restating the key?
I’d be looking to write something like list.whatGoesHere {it * 2}
.
I don’t think there is. The best I could come up with is
list.map { it to it * 2 }.toMap()
There is associate extension function which does the same.
I’m using associate
for lack of anything better.
Should have mentioned that the output doesn’t actually have to be a Map
, a list of Pair
s is also good. So Wasabi’s example would work without .toMap()
.
As far, as I can grasp kotlin’s ideology, you do not have to have anything in the standard library. If you need it, extend it. It does not produce java problem of multiple classes doing the same thing in different libraries, since extensions are not members.
I don’t think any language requires you to have something in the standard library instead of writing it yourself (I assume you refer to extension functions.)
Just seems like an odd omission given all the other utility functions for transforming lists to maps, and Kotlin’s general tendency for lots of very similar utility functions in the standard library (e.g. let/run/apply/also/with for/map/foreach etc).