for
-comprehensions are a great way to wade through both Option
s and conditionals and do something if they’re all populated and the conditions are satisfied.
However, I find myself oftentimes needing to also do something when they’re not populated & satisfied.
This leads to falling back on a very awkward match
syntax, with no real or good substitute, especially if the logic in the for
-comprehension is complex or there is more than one Option
to extract.
Suggestion: expand the if
-statement to allow for for
-comprehension style Option
-extraction.
In its simplest case:
if (a <- aOpt) {
// Use a...
} else {
// Else...
}
would be equivalent to:
aOpt match {
case Some(a) => // Use a...
case _ => // Else...
}
But you could also write e.g.:
if (a <- aOpt && b <- bOpt && a.foo() == b.bar()) {
// Use a & b...
} else {
// Else...
}
which currently requires something like:
aOpt match {
case Some(a) => bOpt match {
case Some(b) if a.foo() == b.bar() => // Use a & b
case _ => // Else 1...
case _ => // Else 2...
}
But that form is both difficult to decipher and has two else branches.
Some random points:
-
In the if-comprehension, an
Option
extraction evaluates totrue
iff theOption.isDefined()
. -
if(!a <- aOpt)
could be a legal statement, in which case it would evaluate totrue
iffOption.isEmpty()
.a
would not be available in thethen
-section of the if-statement, but would be available in theelse
-branch. -
Seq
s would not be allowed - the if-statement can only handleOption
s. -
One could imagine a
for (...) { } else {}
style syntax, but that is a very non-intuitive extension. I’ve also found that whenSeq
s are involved there’s usually both a preamble & postamble to the for-loop, necessitating an outer gate:if (seq.nonEmpty && ...) { ... for (s <- seq) { ... } ... }
. So there’s an impedance mismatch between the need and the capability. -
The
match
statement is extremely powerful and has great applications, but I find it being both verbose and hiding the intention for this particular type of conditional extraction. -
The
if
-comprehension has an intuitive, powerful, clear, concise and backwards-compatible/opt-in syntax and would add something quite useful to the language.
Thoughts?