반응형
Scala FAQ: Can you share some examples of the Scala if/then/else syntax? Also, can you show a function that returns a value from an if/then/else statement?
In its most basic use, the Scala if/then/else syntax is very similar to Java:
if (your test) { // do something } else if (some test) { // do something } else { // do some default thing }
A nice improvement on the Java if/then/else syntax is that you can Scala if/then statements also return a value. As a result, there's no need for a ternary operator in Scala.
This means that you can write if/then statements in Scala like this:
val x = if (a > b) a else b
where you assign the result of your if/then expression to a Scala variable.
Assigning if statement results in a function
You can also assign the results from a Scala if statement in a simple function, like this absolute value function:
def abs(x: Int) = if (x >= 0) x else -x