It is not as simple as omitting the return keyword. In Scala, if there is no return , then the return value is considered the last expression. So, if the last expression is what you want to return, you can omit the return keyword. But if what you want to return is not the last expression, then Scala will not know that you want to return it .
Example:
def f() = { if (something) "A" else "B" }
Here, the last expression of the function f is the if else expression, which evaluates to String. Since no explicit return specified, Scala will output that you want to return the result of this if / else: a String expression.
Now, if we add something after the if / else statement:
def f() = { if (something) "A" else "B" if (somethingElse) 1 else 2 }
Now the last expression is an if / else expression that evaluates to Int. So the return type of f will be Int. If we really wanted it to return String, then we had problems because Scala has no idea what we intended. Thus, we must fix this either by storing the String for the variable and returning it after the second if / else expression, or by changing the order so that the last is the last.
Finally, we can avoid the return keyword even with a nested if-else statement, such as yours:
def f() = { if(somethingFirst) { if (something) // Last expression of `if` returns a String "A" else "B" } else { if (somethingElse) 1 else 2 "C" // Last expression of `else` returns a String }
}
dhg Sep 24 '12 at 7:24 2012-09-24 07:24
source share