What is the purpose of the 'yield' keyword in Scala?

Instruction: Explain how 'yield' is used in Scala loops and provide an example of its usage.

Context: This question explores the candidate's understanding of Scala's for-comprehension and the use of 'yield' for generating collections from loops.

Updated

In a for comprehension, yield specifies the value produced for each successful combination of generators. The result's type and behavior come from the operations supported by those generators, not from yield alone.

@main def yieldExample(): Unit = {
  val numbers = List(1, 2, 3, 4, 5)
  val squares = for (n <- numbers) yield n * n
  val pairs = for {
    n <- List(1, 2)
    label <- List("a", "b")
    if n == 2
  } yield (n, label)
  val absent = for (n <- Option.empty[Int]) yield n * n
  assert(squares == List(1, 4, 9, 16, 25))
  assert(pairs == List((2, "a"), (2, "b")))
  assert(absent == None)
}

The simple list example corresponds to mapping each element. Multiple generators use operations such as flatMap, and guards require filtering support such as withFilter; a comprehension without yield uses iteration such as foreach for effects. The compiler translates comprehension syntax into these operations. It is not the collection library implementing its operations by running a special optimizing yield loop. For comprehensions

Options and futures can also support comprehensions, so the result need not be a collection. Custom types must provide the operations required by the particular comprehension. A guard is not supported automatically just because a type has map and flatMap.

Related Questions