Start learning free

LESSON 275 OF 677 · TUPLES, SORTING & BUILT-INS

zipWithIndex and zip in Scala

Lesson

TL ; DR:

zipWithIndex gives each item with its index. zip walks two ArrayBuffers side by side.


val fruits = scala.collection.mutable.ArrayBuffer("apple", "kiwi", "plum")
val prices = scala.collection.mutable.ArrayBuffer(3, 1, 2)

for ((fruit, i) <- fruits.zipWithIndex) {
    println(s"${i + 1}. $fruit")    // 1. apple, 2. kiwi, 3. plum
}

for ((fruit, price) <- fruits.zip(prices)) {
    println(s"$fruit $price")       // apple 3, kiwi 1, plum 2
}


Full lesson:

You have looped with for (i <- meals.indices). Then meals(i) gave the item. Scala has a shorter way to get both.

zipWithIndex pairs each item with its index. The loop unpacks each pair into two names, as val (name, age) = pet does.

for ((meal, i) <- meals.zipWithIndex) {
    println(s"$i $meal")
}

Mind the order. The item comes first and the index second. Writing (i, meal) swaps the names, and the output comes out wrong.

The index starts at 0, so print i + 1 for a numbered list.

a.zip(b) walks two ArrayBuffers side by side. It pairs the first item of a with the first item of b. Then it pairs the second items, and so on. Each pair is a tuple.

for ((fruit, price) <- fruits.zip(prices)) {
    println(s"$fruit costs $price")
}

zip stops at the end of the shorter one. The extra items are skipped, with no error.

The two work together. Zip first, then number the pairs with zipWithIndex. Each item is then a pair and an index, so the names nest.

for (((fruit, price), i) <- fruits.zip(prices).zipWithIndex) {
    println(s"${i + 1}. $fruit costs $price")
}

Your task

A quiz show keeps its players in the ArrayBuffer players. Their points are in scores, in the same order.

First, print the players as a numbered list from 1, like 1. Ana. Use zipWithIndex.

Then print each player with their points, like Ana has 12 points. Use zip.

Expected output:

1. Ana
2. Ben
3. Cleo
Ana has 12 points
Ben has 9 points
Cleo has 15 points
STEP 1 OF 4
    Ctrl + Enter to check