Skip to content

Scala IF...ELSE

Conditional logic in Scala is handled using if, else if, and else. A crucial aspect of Scala is that if-else constructs are expressions, meaning they evaluate to a value.

Executes a block of code only if a boolean condition is true.

if (booleanCondition) {
// Code block executes if condition is true
}
val temperature = 25
if (temperature > 30) {
println("It's hot!")
}
// If temperature is not > 30, nothing happens here.

Provides an alternative block to execute if the condition is false. Since it’s an expression, its result can be assigned to a variable.

val result = if (booleanCondition) {
// Value or block evaluating to a value if true
} else {
// Value or block evaluating to a value if false
}

Important: Both branches (if and else) must return values of compatible types for the overall expression to have a well-defined type. If they don’t, the compiler will infer a common supertype, potentially Any.

val age = 18
val message = if (age >= 18) {
"Adult"
} else {
"Minor"
}
println(s"Status: $message") // Output: Status: Adult
// Example with different return types (results in Any type)
val result: Any = if (age < 10) {
"Child"
} else {
false // Boolean is not compatible with String, result is Any
}
println(s"Mixed result type: $result") // Output: Mixed result type: false

If the else part is omitted and the condition is false, the expression implicitly results in Unit (()).

val unitResult = if (age < 10) { println("Young") }
println(s"Unit result: $unitResult") // Output: Unit result: ()

Allows checking multiple conditions in sequence.

val result = if (condition1) {
// Value for condition1 true
} else if (condition2) {
// Value for condition2 true
} else if (condition3) {
// Value for condition3 true
} else {
// Value if none of the above conditions are true
}

The first condition that evaluates to true determines the executed block and the resulting value. The final else is optional, but recommended if you need a value in all cases (otherwise the result type might become Any or Unit).

val score = 75
val grade = if (score >= 90) {
'A'
} else if (score >= 80) {
'B'
} else if (score >= 70) {
'C'
} else if (score >= 60) {
'D'
} else {
'F'
}
println(s"Score: $score, Grade: $grade") // Output: Score: 75, Grade: C

You can nest if-else expressions within each other, but deep nesting can become hard to read. Consider using match expressions for complex conditional logic.

val isMember = true
val userAge = 25
val discount = if (isMember) {
if (userAge > 60) {
0.20 // 20% discount for senior members
} else {
0.10 // 10% discount for regular members
}
} else {
0.0 // No discount for non-members
}
println(s"Discount: ${discount * 100}%") // Output: Discount: 10.0%

Because if-else is an expression, it integrates naturally into functional programming styles, allowing concise assignment and use within other expressions.