mapIndexed

map 사용중에 인덱스가 필요한 경우 사용한다.

public inline fun <T, R> Iterable<T>.mapIndexed(transform:
(index: Int, T) -> R): List<R> {
    return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}

public inline fun <T, R, C: MutableCollection<in R>
Iterable<T>.mapIndexedTo(destination: C, transform: (Index: Int, T) -> R): C {
    val index = 0
    for (item in this)
        destination.add(transform(index++, item))
    return destination
}


val list = listOf(Person("a", 10), Person("b", 30), Person("c", 15))
println(list.mapIndexed{ index, value -> "index $index = ${value.name}" })
// [index 0 = a, index 1 = b, index 2 = c]

Last updated