1. Overview

The if-else construct is one of the most basic conditional constructs in programming languages. It lets us execute a piece of code based on the value of a condition. In this tutorial, we’re going to cover conditional expressions in Scala.

2. if Expression

The syntax of an if expression in Scala is similar to other imperative languages like Java or C++:

if (<condition expression>) {
  <expression>
} else {
  <expression>
}

The condition expression here denotes an expression that evaluates to a boolean. If the boolean condition evaluates to true, the first expression is executed. Otherwise, the second expression is executed.

The else part of an if expression is optional. It’s perfectly valid not to have an else expression.

Let’s look at a basic if expression:

def max(a: Int, b: Int): Unit = {
  var max: Int = a

  if (b > a) {
    max = b
  }

  printf("Maximum is %d", max)
}

Here, we define a function max that prints the maximum of two given inputs. We first initialize max with the value of a. Then we check if b is greater than a and if so, we assign to max the value of b. Finally, we use the value of max to print the maximum value.

Let’s look at an example that uses an if expression with an else expression:

if (10 % 2 == 0) {
  printf("Number is even")
} else {
  printf("Number is odd")
}

As 10 is divisible by 2, the code prints:

Number is even

We can skip the curly braces if there is only one statement in the expression. They are required only when there are multiple statements in an expression. However, the Scala Style Guide recommends using the curly braces to make code our more readable.

2.1. Nested if Expression

Each of the expressions in an if can be further nested with if-else expressions to create multiple if-else blocks. Let’s take a look at a nested if expression:

val number = 10
if (number == 0) {
  printf("Number is zero")
} else if (number > 100) {
  printf("Number is greater than 100")
} else {
  printf("Number is %d", number)
}

The value of number is 10. So, the first two if conditions evaluate to false, and the last else expression is executed:

Number is 10

2.2. Return Value and Type

Scala’s if is different from other languages in one crucial aspect.

In Scala, all statements are expressions that return a value. The value of the last statement determines the value of an expression. The if expression is no different — it always returns a value.

So, we can assign the result of an if expression to a value. We can write the previous max function as:

def max(a: Int, b: Int): Int = {
  if (b > a) {
    b
  } else {
    a
  }
}

Here, we directly return the value of the if expression, which, in turn, returns the maximum of a and b.

The return type of an if expression is the closest supertype of the two branch expressions. The return type of the above example is Int because both of the branches return an Int.

An if expression without an else expression also returns a value. When there is no else expression, the return type is Any.

We can easily verify that in the Scala REPL:

scala> val result = if (false) "failed"
result: Any = ()

3. Idiomatic Conditional Initialization

Using an if expression is the idiomatic way to initialize variables in Scala conditionally. Not only does it result in writing less code, but it uses a val instead of a var.

Having a val helps us avoid mutability and increases code readability. It tells our users that, once initialized, the value won’t change:

val max: Int = if (10 > 100) {
  10
} else {
  100
}

Here, max gets initialized with the value 100 because 10 is not greater than 100.

Unlike Java, Scala does not have a ternary operator to write terse if-else expressions.

As Scala’s if expressions always return a value, having a ternary operator would be redundant. This is Scala’s way of doing more with less.

4. Conclusion

In this article, we went through Scala’s if expression and its syntax. We learned that an if expression always returns a value, and we saw how to use it to initialize a variable conditionally. As always, all code examples are available over on GitHub.


« 上一篇: Scala 中的变异
» 下一篇: Scala 集合指南