Google News
logo
Scala - Interview Questions
What is the difference between 'foreach' and 'map' methods on a collection in Scala?
In Scala, both the `foreach` and `map` methods are available on collections, but they serve different purposes:

1. `foreach` method :
   * Syntax: `foreach(f: A => Unit): Unit`
   * Purpose: The `foreach` method is used to iterate over each element in a collection and apply a provided function `f` to each element.
   * Return type: `Unit`
   * Side effect: The function `f` is executed for each element in the collection, typically used for performing side effects such as printing, updating mutable state, or performing I/O operations.
   - Example :
     val numbers = List(1, 2, 3, 4, 5)

     numbers.foreach(num => println(num * 2))​

     In this example, the `foreach` method is called on the `numbers` list, and for each element, the provided function `num => println(num * 2)` is applied. It prints the doubled value of each number in the list.

2. `map` method :
   * Syntax: `map[B](f: A => B): List[B]`
   * Purpose: The `map` method is used to transform each element in a collection using a provided function `f` and return a new collection with the transformed elements.
   * Return type: The return type of `map` is a new collection of the transformed elements.
   * Side effect: `map` does not have any side effects and is purely a transformation operation.
   - Example :
     val numbers = List(1, 2, 3, 4, 5)

     val doubledNumbers = numbers.map(num => num * 2)​

    
In this example, the `map` method is called on the `numbers` list, and for each element, the provided function `num => num * 2` is applied to double the value. It returns a new list `doubledNumbers` with the transformed elements.

The main difference between `foreach` and `map` is their purpose and return value:

* `foreach` is used for iteration and applying a function with side effects to each element. It returns `Unit` and is typically used when you want to perform actions on each element of the collection without producing a new collection.

* `map` is used for transformation and applying a function to each element, returning a new collection with the transformed elements. It does not have side effects and is useful when you want to transform the elements of a collection into a new collection.

Both methods are powerful tools for working with collections in Scala, but their use cases differ based on whether you want to perform side effects or create a new collection with transformed elements.
Advertisement