Home > Software design >  How did this code using zip() got the indexes of the elements in the list?
How did this code using zip() got the indexes of the elements in the list?

Time:10-15

I'm solving exercises for a programming book in Kotlin. The task is to implement function using "zip()" and return a "List" of Pairs, where the first item in a "Pair" is the element, and the second item is the index of that element.

I solved the exercise, the solution works but I cannot understand the book solution.

Here is mine solution:

fun zipWithIndex(listToTake: List<Any>): List<Pair<Any, Any>> {
    val finalList = mutableListOf<Any>()
    var num = 0
    for(element in listToTake) {
        finalList  = num
        num   
    }
    return (listToTake zip finalList)
}
fun main() {
    val listToCall = listOf<String>("a", "b", "c")
    println(zipWithIndex(listToCall))
}

And here is the book solution:

fun <T> List<T>.zipWithIndex(): List<Pair<T, Int>> =
  zip(indices)

fun main() {
  val list = listOf('a', 'b', 'c')
  list.zipWithIndex() eq
    "[(a, 0), (b, 1), (c, 2)]"
}

Can somebody please explain how does the book solution get the indexes of the elements in the list or tell me the topic that I need to read about to figure out how the code from the book works.

Thanks in advance for any help.

CodePudding user response:

indices is a property of every kotlin List: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/#extension-properties

It's an IntRange of all valid indices, so essentially the range (https://kotlinlang.org/docs/ranges.html) equivalent of [0, 1, 2]. An IntRange is an Iterable, so it can be zipped with (the third zip overload in the api docs of list).

So it is equivalent to the zip you did, except you constructed [0, 1, 2] yourself while they used the pre-existing property of the List.

They also defined an extension function on List (https://kotlinlang.org/docs/extensions.html#extension-functions) instead of passing the list as a parameter.

  • Related