One of my issue is – if we rely on implicit return, it is error prone,
eg.
def foo(bar: Int): Int =
{
if (f1(bar)) 0
if (f2(bar)) 1
else -1
}
Sometimes we just forgot the else statement, in order to fix this issue, curly brace is enforced like, .e.g
def foo(bar: Int): Int =
{
if (f1(bar)) {
0
} else if (f2(bar)) {
1
} else {
-1
}
}
But the new style is too verbose IMHO, any way to fix?
As a practical matter, I never have this problem, and I make loads of silly mistakes. I suspect that you are entirely capable of learning to not skip the else statement. (Note that braces don’t help anything; you can still skip the
elsein the middle one.)If you really, really find this a problem, you can either abuse the
matchstatement:which will prevent you from making any mistakes. Or you can write yourself a utility method:
This is a little messy for long expressions, so you could also (use
:pasteto stick this in the REPL in one big block if you want it to work there):Now the only trick is that you have to use
:pastein the REPL to write a multi-line statement, and put the continuation on the end of the previous line:You can also use
Then { 0on one line and start up again with} Oron the next, or write everything with parens/braces and dots (which is REPL-friendly):Anyway, all this trickery is a good illustration of how to build sophisticated DSLs with Scala, but not really the best way to solve your problem. You should just learn to be a little more careful with if/else statements; otherwise, people are going to be puzzled as to why you’re not doing things the standard way. (And if it’s performance-critical, it may be slow–
matchis pretty good, but theIfwizardry is not good in a high-performance loop.)