Scala if then else syntax (and returning a value from an if statement)

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 similar to Java:

if (your test) {
  // do something
else if (some test) {
  // do something
else {
  // do some default thing

Using if/then like a ternary operator

A nice improvement on the Java if/then/else syntax is that Scala if/then statements return a value. As a result, there’s no need for a ternary operator in Scala., which means that you can write if/then statements like this:

val x = if (a > b) a else b

where, as shown, you assign the result of your if/then expression to a variable.

Assigning if statement results in a function

You can also assign the results from a Scala if expression in a simple function, like this absolute value function:

def abs(x: Int) = if (x >= 0) x else -x

As shown, the Scala if/then/else syntax is similar to Java, but because Scala is also a functional programming language, you can do a few extra things with the syntax, as shown in the last two examples.