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?

Scala 2 if/then/else syntax

In its most basic use, the if/then/else syntax in Scala 2 is similar to Java:

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

Scala 3 if/then/else syntax

In Scala 3 the if/then/else syntax is a little different:

if your-test then
    // do something
    // here
else if some-test then
    // do something
    // else here
else
    // do some
    // default thing

Note that in Scala 3, the parentheses and curly braces are not required. You use the then keyword at the end of each statement, and then indent your code in each block.

Also note that in these examples I am a “four space indent” kind of guy. Most other people prefer two spaces, so if you prefer that, go ahead and use it.

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 Scala 2 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.

In Scala 3 that now looks like this:

val x = if a > b then a else b

Assigning ‘if’ statement results in a function

Because the Scala if/then syntax can be used as a ternary operator — an expression, really — it can be used as the body of a Scala function.

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

def abs(x: Int): Boolean = 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.

Here’s what that looks like in Scala 3:

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