Search code examples
scalafor-comprehension

Converting nested for loops into for comprehension


I can collect the results at the inner-most for body into a List[Output] and return them. But I want to use yield. How can this method be converted into using for-yield pattern:

def useForComprehension(input : Input): List[Output] = {        
  for (o <- splitInputIntoPieces(input)) {
    for (restResults <- useForComprehension(subtract(input, o)) ) {
        for (w <- f3(o)) {
          yield w::restResults // !!!!! Error
        }
    }           
  }    
}

Solution

  • In Scala, nested iteration is handled by adding additional <- clauses.

    For example, let's say we have two lists l1 and l2 and we want generate over every pair of elements (x,y) where x is in l1 and y is in l2. The syntax in Scala is:

    for { x <- l1
          y <- l2
        } yield (x,y)
    

    When no yield keyword follows the for then the entire expression results in a type of Unit, which is the source of your type error. This is useful for performing side effects on the iteration, for example

    for { x <- l1
          y <- l2
        } println((x,y))
    

    For more information on for comprehensions see What is Scala's yield?