I found a strange statement

This can work:

scala> zz
val res65: List[Boolean] = List(true, false, false, true)

scala> for ( x <- zz; if false ) yield x
val res66: List[Boolean] = List()

But this can’t work:

scala> for ( x <- zz ) if false yield x
       error: '(' expected but 'false' found.

From my own thought, the second should be working. :slight_smile:

The first one works, but always produces an empty list. Did you perhaps mean:
for (z <- zz; if !x) yield x ?

The second one is wrong syntax.

1 Like

This does appear to be working as intended. I’ve put together a small scastie with comments. Scastie - An interactive playground for Scala.

The reason you get that particular error message is that, in the body of the for comprehension; where body is defined as for (body) statement; an “if” is treated as a guard, with a guard you do not need to declare brackets around the boolean expression.

outside of the for comprehension body (or pattern match), and “if” is not a guard and must be declared with braces around the boolean expression. This is to avoid ambiguity

if true "str" is invalid
if (true) "str" is valid

1 Like

In this case even () added the syntax doesn’t work:

scala> for (x <- zz) if (false) yield x
       error: illegal start of simple expression

No, this does not work since it is invalid.

There are two kinds of for statements, for with yield and without.

You cannot use yield inside an if expression inside the body of a for statement, the syntax always is

for (..$enumeratorsnel) $expr

// OR

for (..$enumeratorsnel) yield $expr
1 Like