1. Introduction
Iterating over a list with access to both the element and its index is a common requirement in Scala programming. Scala provides several ways to achieve this, allowing developers to choose the most suitable approach for their specific scenario. This post will explore various methods for iterating over a Scala list with an index.
2. Program Steps
1. Define a Scala List.
2. Demonstrate different methods to iterate over the list with access to the index, including using zipWithIndex, for comprehension, and explicit indexing.
3. Print the results to showcase how each method works.
3. Code Program
object ListWithIndexIterationDemo extends App {
val fruits = List("Apple", "Banana", "Cherry")
// Using zipWithIndex
println("Iterating with zipWithIndex:")
fruits.zipWithIndex.foreach { case (fruit, index) =>
println(s"Index $index is $fruit")
}
// Using for comprehension
println("\nIterating with for comprehension:")
for ((fruit, index) <- fruits.zipWithIndex) {
println(s"Index $index is $fruit")
}
// Using explicit indexing
println("\nIterating with explicit indexing:")
for (index <- fruits.indices) {
println(s"Index $index is ${fruits(index)}")
}
}
Output:
Iterating with zipWithIndex: Index 0 is Apple Index 1 is Banana Index 2 is Cherry Iterating with for comprehension: Index 0 is Apple Index 1 is Banana Index 2 is Cherry Iterating with explicit indexing: Index 0 is Apple Index 1 is Banana Index 2 is Cherry
Explanation:
1. zipWithIndex pairs each element of the list with its index, creating tuples. We then iterate over these tuples using foreach.
2. For comprehension provides a more readable syntax for the same operation, unpacking the tuple directly in the loop definition.
3. Explicit indexing involves iterating over the indices of the list and accessing elements by their index using fruits(index). This method is closer to traditional indexed iteration found in languages like Java or C#.
Comments
Post a Comment