capt.swag
capt.swag

Reputation: 10651

Better way to write the following code in Kotlin?

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

Answers (2)

capt.swag
capt.swag

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

Sergei Zarochentsev
Sergei Zarochentsev

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

Related Questions