TL ; DR:
withIndex() gives each item with its index. zip walks two lists side by side.
val fruits = mutableListOf("apple", "kiwi", "plum")
val prices = mutableListOf(3, 1, 2)
for ((i, fruit) in fruits.withIndex()) {
println("${i + 1}. $fruit") // 1. apple, then 2. kiwi, then 3. plum
}
for ((fruit, price) in fruits.zip(prices)) {
println("$fruit $price") // apple 3, then kiwi 1, then plum 2
}
Full lesson:
You have looped with for (i in 0 until meals.size). Then meals[i] gave the item. Kotlin has a shorter way to get both.
withIndex() gives each item together with its index. The loop unpacks the two, as val (name, age) = pet unpacks a pair.
for ((i, meal) in meals.withIndex()) {
println("$i $meal")
}
The index comes first. It starts at 0, so print i + 1 for a numbered list.
a.zip(b) walks two lists 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. The result is a list of Pairs.
for ((fruit, price) in fruits.zip(prices)) {
println("$fruit costs $price")
}
zip stops at the end of the shorter list. The extra items are skipped, with no error.
The two work together. fruits.zip(prices).withIndex() gives an index and a pair each time.
Watch out here. A for line can't unpack a pair inside a pair. Unpack the pair on the loop's first line instead.
for ((i, pair) in fruits.zip(prices).withIndex()) {
val (fruit, price) = pair
println("${i + 1}. $fruit costs $price")
}
Your task
A quiz show keeps its players in the list players. Their points are in scores, in the same order.
First, print the players as a numbered list from 1, like 1. Ana. Use withIndex().
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 pointsFree plan: 30 tutor messages. PRO is unlimited.
