What is the difference between map, flatMap, and foreach in Scala?

Updated May 24, 2026

Short answer

map transforms values, flatMap flattens nested contexts, foreach is for side effects.

Deep explanation

map applies a function to each element. flatMap is used when each transformation returns a container (Option/List/Future) and flattens the result. foreach is used for side-effecting operations without returning a new collection.

Real-world example

Used in ETL pipelines where transformations may produce optional or multiple outputs.

Common mistakes

  • Using map when flatMap is required causing nested collections.

Follow-up questions

  • Why does flatMap avoid nested structures?
  • Can foreach return values?

More Scala interview questions

View all →