A closest equvalent of [42 | i == j]
would probably be for (x <- List(42) if i == j) yield x
.
for (if i == j) yield 42
is illegal because a filter (if
part) must follow some generator (x <- List(42)
in my example).
Scala language specification states (6.19 For Comprehensions and For Loops):
Syntax:
Expr1 ::= ‘for’ (‘(’ Enumerators ‘)’ | ‘{’ Enumerators ‘}’)
{nl} [‘yield’] Expr
Enumerators ::= Generator {semi Enumerator}
Enumerator ::= Generator
| Guard
| ‘val’ Pattern1 ‘=’ Expr
Generator ::= Pattern1 ‘<-’ Expr [Guard]
Guard ::= ‘if’ PostfixExpr
As you can see, there's at least one generator required in Enumerators
.
EDIT:
By the way, I think if (i == j) List(42) else Nil
is the right thing to do since it is not Haskell. It is clean and most likely faster because it constructs a list just once and doesn't call any additional methods.
My example is translated by compiler into List(42) withFilter (x => i == j) map (x => x)
(it actually may be optimized, I'm not sure) and can be abbreviated to List(42) filter (x => i == j)
. You can see, it constructs the initial list, than calls a method which creates a new list, and this method takes anonymous function, which in Scala is also an object (but probably it is also optimized). I think it is inefficient way to do such a simple job.