Reputation: 10651
I've this following function, which maps ids to a list of Strings
private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String>> {
var id = 4
return resourcesList.map { resource ->
id++
id to resource
}
}
The id starts from 5 as you can see here. I can make this code look cleaner if id started from 0. Just like this
private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
index to resource
}
Is there some Kotlin function to achieve the first result without the use of var id. Maybe some function whose index starts at 5?
Upvotes: 3
Views: 116
Reputation: 10651
From the comment by @al3c
private fun doIdMapping(resourcesList: List<String>): List<Pair<Int, String> = resourcesList.mapIndexed { index, resource ->
index + 5 to resource
}
This was probably easier than I thought.
Upvotes: 2
Reputation: 827
You can use zip function and int-range:
private fun doIdMapping(resourcesList: List<String>, startIndex: Int = 5)
= (startIndex..startIndex + resourcesList.size).zip(resourcesList)
Upvotes: 1