Learn Scala 3 Fast: Constructs: if/then/else

Now that we’ve covered that background, we can start looking at Scala’s control structures. We’ll start with the Scala 3 if/then syntax.

Given two variables a and b, this is how you write a one-line if statement in Scala 3:

if a == b then println(a)

Similarly, this is how you put multiple lines of code after an if:

if a == b then
    println("a equals b, as you can see:")
    println(a)

When you need an else clause, add it like this:

if a == b then
    println("a equals b, as you can see:")
    println(a)
else
    println("a did not equal b")

And when you need “else if” clauses, add them like this:

if a == b then
    println("a equals b, as you can see:")
    println(a)
else if a == c then
    println("a equals c:")
    println(a)
else if a == d then
    println("a equals d:")
    println(a)
else
    println("hmm, something else ...")

It can be easier to read if statements with an end if at the end of them, so you can always add that, if you prefer:

if a == b then
    println("a equals b")
else if a == c then
    println("a equals c:")
else if a == d then
    println("a equals d:")
else
    println("hmm, something else ...")
end if

In this lesson I demonstrated if statements, meaning that the if/then construct is used for a side effect, which in this case was printing output. In the next lesson you’ll see how to use if expressions, which are if/then constructs that return a result.

Exercises

The exercises for this lesson are available here.

books by alvin