Michelle Garrett

If/Else Expressions in Scala

scala

In Scala, there are If/Else expressions rather than If/Else statements. This means that the If/Else block actually yields a value, rather than just performing actions.

The fact that Scala has If/Else expressions aligns better with functional programming style. Using expressions reduces the number of variables that must be declared, making it easier to achieve immutability.

An If/Else expression looks like:

  val a = 10
val b = 20

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

// if expression yields 20
// z: Int = 20

It is possible to ignore the returned value, and use If/Else as a statement, however this is not best practice as it encourages side effects and mutation. Example:

  val a = 10
val b = 20
var m = 0

if (a > b) {
m = a
} else {
m = b
}

// if expression yields 20, but this is ignored
// variable m is mutated inside the If/Else block
// m: Int = 20