I feel like that we need to improve the for-comprehension itself. It should be generalized to match the other syntactic/control flow constructs in Scala.
The regular Scala constructs, like val
, if
, throw
would have their counterparts with !
, like val!
(currently <-
, flatMap
), if!
(ifM
), throw!
(raiseError
), etc…
The beauty of this approach is that it builds on top of the already existing concept of for-comprehensions and uses similarly named keywords for analogous things (there is just !
appended), so it’s highly regular.
for
val! x = fetchData
val! y = if! isFine(x)
then
for
val! defatils = fetchDetails(x)
yield details + localDetails(x)
else
throw! RuntimeException(s"$x is not fine")
yield y
ordinary code analogue | for-comprehension | sugar for |
---|---|---|
val ... = ... |
val! ... = ... (legacy ... <- ... ) |
flatMap |
if ... then ... else ... |
if! ... then ... else ... |
ifM |
throw ... |
throw! ... |
raiseError |
try ... catch ... |
try! ... catch ... |
handleErrorWith |
while ... do ... |
while! ... do ... |
whileM |
… |
This is how other languages do it, like F#. It also uses !
appended, although Scala could choose other symbol or prepending it instead of appending it, but that’s an insignificant detail at this point.