E020: For 컴프리헨션에서 Yield 또는 Do 필요

E020: For 컴프리헨션에서 Yield 또는 Do 필요 (Yield Or Do Expected In For Comprehension)

이 에러는 열거자(enumerator) 주변에 괄호가 없는 for 컴프리헨션에서 yielddo 키워드가 빠졌을 때 발생해요.

출처: Scala 3 Reference

본문

for 컴프리헨션의 열거자가 괄호나 중괄호로 감싸져 있지 않으면, 열거자 구간 뒤에 do 또는 yield 문이 반드시 필요해요.

괄호를 생략하고 이렇게 쓰면 타이핑을 줄일 수 있어요:

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

다음 대신:

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

하지만 yield 키워드는 여전히 필요해요.

아무것도 산출(yield)하지 않고 단순히 부수 효과(side effect)만 수행하는 for 컴프리헨션도 괄호 없이 쓸 수 있지만, do 키워드를 포함해야 해요.

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)

더 알아보기

  • for 컴프리헨션과 do/yield 문법은 "For Comprehensions" 관련 문서를 참고하세요.