Explain the significance of 'for-yield' comprehensions in Scala.

Instruction: Discuss how 'for-yield' comprehensions are used in Scala and provide examples of their applications.

Context: This question assesses the candidate's understanding of Scala's for-comprehension, a syntactic sugar that simplifies working with collections and other monadic types.

Updated

A for expression with yield composes operations such as map, flatMap and, when a guard requires it, withFilter. Its result and sequencing semantics come from the participating type; it does not necessarily produce a collection.

@main def comprehensionExample(): Unit = {
  val pairs = for {
    left <- List(1, 2)
    right <- List(3, 4)
    if left + right == 5
  } yield (left, right)
  assert(pairs == List((1, 4), (2, 3)))

  val amount: Either[String, Int] = Right(4)
  val price: Either[String, Int] = Right(3)
  val total = for {
    n <- amount
    p <- price
  } yield n * p
  assert(total == Right(12))
}

The list example expresses ordered nested traversal and filtering. The Either example composes successful values and propagates a Left; it does not accumulate every error. Its shape is equivalent to amount.flatMap(n => price.map(p => n * p)). Not every type with map and flatMap supports guards: Either does not provide withFilter. For-comprehensions

With futures, constructing independent futures before the comprehension permits their work to overlap. Constructing a later future inside a dependent generator delays that construction until the earlier result is available. The syntax does not make already-started futures execute sequentially or guarantee parallelism. A comprehension without yield uses foreach for its traversal rather than building a transformed result.

Related Questions