If Else in Scala

Branching with if and else in Scala is straightforward.

object IfElseExample {
  def main(args: Array[String]): Unit = {
    // Here's a basic example.
    if (7 % 2 == 0) {
      println("7 is even")
    } else {
      println("7 is odd")
    }

    // You can have an `if` statement without an else.
    if (8 % 4 == 0) {
      println("8 is divisible by 4")
    }

    // Logical operators like && and || are often useful in conditions.
    if (8 % 2 == 0 || 7 % 2 == 0) {
      println("either 8 or 7 are even")
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    val num = 9
    if (num < 0) {
      println(s"$num is negative")
    } else if (num < 10) {
      println(s"$num has 1 digit")
    } else {
      println(s"$num has multiple digits")
    }
  }
}

To run the program:

$ scala IfElseExample.scala
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Scala, you don’t need parentheses around conditions, but they are allowed. Curly braces are required for multi-line blocks but can be omitted for single-line expressions.

Unlike some other languages, Scala does have a ternary-like operator in the form of an if-else expression:

val result = if (condition) trueValue else falseValue

This can be used for concise conditional assignments.