How does Scala's 'for-comprehension' differ from traditional for loops?

Instruction: Compare Scala's 'for-comprehension' with traditional for loops, highlighting the differences and advantages.

Context: Assess how Scala for-comprehensions use map, flatMap, withFilter and foreach, and distinguish result-producing composition from effectful iteration.

Updated

A Scala for-comprehension expresses operations through methods supplied by its input types. With yield, generators commonly use flatMap and map, while guards use withFilter; without yield, iteration uses foreach for effects. It is not an automatic guarantee of purity, parallelism or a speed improvement.

@main def comprehensionExample(): Unit = {
  val pairs = for {
    x <- List(1, 2)
    y <- List(10, 20)
    if x + y > 11
  } yield (x, y)
  assert(pairs == List((1, 20), (2, 10), (2, 20)))

  var total = 0
  for (x <- List(1, 2, 3)) total += x
  assert(total == 6)
}

The first expression builds a result list from nested generators. The second explicitly performs a side effect. A conventional imperative loop exposes its iteration and state changes directly; a comprehension makes the composition easier to read, but its meaning comes from the participating methods.

The same notation works for supported types such as Option, whose None skips dependent steps, and Either, whose Left propagates a failure. Not every type supports guards or every possible combination of containers. You cannot infer that a custom type is a lawful monad merely because it supports a particular comprehension. For-comprehensions and required operations

Use yield when producing a transformed result, and use an explicit effectful iteration when that is the intent. For large workloads, inspect intermediate allocations and the collection's strict or lazy evaluation semantics before making performance claims.

Related Questions