E020: Yield Or Do Expected In For Comprehension

This error is emitted when a for comprehension without parentheses around the enumerators is missing a yield or do keyword.

When the enumerators in a for comprehension are not placed in parentheses or braces, a do or yield statement is required after the enumerators section.

You can save some keystrokes by omitting the parentheses and writing:

val numbers = for i <- 1 to 3 yield i

instead of:

val numbers = for (i <- 1 to 3) yield i

but the yield keyword is still required.

For comprehensions that simply perform a side effect without yielding anything can also be written without parentheses but a do keyword has to be included.


Example

val xs = for i <- 1 to 10

Error

-- [E020] Syntax Error: example.scala:1:25 -------------------------------------
1 |val xs = for i <- 1 to 10
  |                         ^
  |                         yield or do expected
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | When the enumerators in a for comprehension are not placed in parentheses or
  | braces, a do or yield statement is required after the enumerators
  | section of the comprehension.
  |
  | You can save some keystrokes by omitting the parentheses and writing
  |
  | val numbers = for i <- 1 to 3 yield i
  |
  |   instead of
  |
  | val numbers = for (i <- 1 to 3) yield i
  |
  | but the yield keyword is still required.
  |
  | For comprehensions that simply perform a side effect without yielding anything
  | can also be written without parentheses but a do keyword has to be
  | included. For example,
  |
  | for (i <- 1 to 3) println(i)
  |
  | can be written as
  |
  | for i <- 1 to 3 do println(i) // notice the 'do' keyword
   -----------------------------------------------------------------------------

Solution

// Add yield to produce a collection
val xs = for i <- 1 to 10 yield i * 2
// Use do for side effects
def example() = for i <- 1 to 10 do println(i * 2)
// Or use parentheses (then yield is optional for producing values)
val xs = for (i <- 1 to 10) yield i * 2
// With braces for multiple generators
val pairs = for {
  i <- 1 to 3
  j <- 1 to 3
} yield (i, j)