1. Introduction
Scala provides a rich set of tools in order to iterate over collections. It offers an extensive collections framework with a unique fusion of object-oriented and functional programming paradigms which allows us to work efficiently with data structures.
In this article, we’ll go over two of the main techniques to iterate over collections in Scala: foreach and for comprehension. We’ll also explore the differences between the two and when to pick one over the other.
2. Using foreach To Iterate Over Collections
Scala collections come with a built-in method called foreach which allows for a very simple iteration process. By applying a function to each element in the collection, the foreach method eliminates the need for explicit loops and enables concise execution of operations on each element.
Consider the following example:
val numbers = List(1, 2, 3, 4, 5)
numbers.foreach(num => println(num))
This example iterates through the array, printing each element to the console in a straightforward and concise manner, a common foreach usage. Since foreach accepts a non-returning function and yields a Unit result, it is typically employed for its side effects, such as the console output in the above example.
3. Using for Comprehension To Iterate Over Collections
Scala’s for comprehension offers a powerful and intuitive method for iterating over collections. It syntactically combines map, flatMap, and filter, resulting in code that resembles natural language. Unlike a traditional looping construct, for comprehension is transformed by the compiler into map, flatMap, and filter operations. This makes it compatible with any collection that implements the foreach method.
Let’s take a look at an example:
val numbers = List(1, 2, 3, 4, 5)
val doubledNumbers = for (num <- numbers) yield num * 2
println(doubledNumbers) // Output: List(2, 4, 6, 8, 10)
In this example, we’re using for comprehension to iterate over a collection of numbers, multiply them by two, and return the result into a variable as a new collection. The yield keyword is used to specify the transformation to be applied to each element. Note that the type of the resulting collection in the for comprehension will match the type of the original collection.
4. Comparing Both Approaches
A significant distinction between these two approaches lies in their return values. The foreach method lacks a meaningful result, making it primarily suited for executing actions on each element within a collection. In contrast, for comprehensions are designed to serve computation and transformation purposes, rather than facilitating side-effecting operations. The choice between these techniques ultimately depends on the specific requirements of our code.
5. Conclusion
In summary, when deciding between foreach and for comprehensions, we should consider whether we need side effects or a transformed collection. It’s also worth noting that a hybrid approach can offer benefits, combining the ease of foreach with the versatility of for comprehensions for more complex computations.
Code examples are available over on GitHub.