Scala Wart: For-comprehensions syntax restrictions
See original GitHub issueOpening this issue, as suggested by Martin, to provide a place to discuss the individual warts brought up in the blog post Warts of the Scala Programming Language and the possibility of mitigating/fixing them in Dotty (and perhaps later in Scala 2.x). These are based on Scala 2.x behavior, which I understand Dotty follows closely, apologies in advance if it has already been fixed
As mentioned above, you cannot have def
s, class
es, or imperative
statements in the generators of a for-comprehension:
scala> for{
| i <- Seq(1)
| println(i)
| j <- Seq(2)
<console>:4: error: '<-' expected but ';' found.
j <- Seq(2)
^
This is a rather arbitrary restriction, and as far as I can tell doesn’t serve
any purpose, and forces you to put random _ =
prefixes on your statements to
make things compile:
scala> for{
| i <- Seq(1)
| _ = println(i)
| j <- Seq(2)
| } yield j
1
res0: Seq[Int] = List(2)
There really isn’t any reason that this shouldn’t work out-of-the-box, and convert say:
for{
i <- Seq(1)
def debug(s: Any) = println("Debug " + s)
debug(i)
j <- Seq(2)
debug(j)
k <- Seq(3)
} yield i + j + k
Into
Seq(1).flatMap{ i =>
def debug(s: Any) = println("Debug " + s)
debug(i)
Seq(2).flatMap{ j =>
debug(j)
Seq(3).map{ k =>
i + j + k
}
}
}
Issue Analytics
- State:
- Created 6 years ago
- Reactions:12
- Comments:8 (5 by maintainers)
Top GitHub Comments
see #1982, too
I don’t see a lot of appetite to tackle this, since it would require major changes to the principle and implementation of parsing. So it would be a high effort project that also comes with high risk of failure.