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 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

As you can see, the Scala if/then/else syntax is similar to Java, but given that Scala is also a functional programming language, you can do a few extra things with the syntax, like this last example.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.