Scala if, if-else, and else-if Conditions
Conditional statements let a Scala program choose which code to execute based on a Boolean condition. A condition must evaluate to either true or false.
Scala supports the following conditional forms:
ifstatementif-elsestatementif-else-ifladder
Unlike many languages, Scala also treats if as an expression. This means an if-else construct can produce a value that you assign to a variable or return from a method.
Scala IF Statement
The syntax of Scala if statement is
if(boolean_expression) {
// statements inside if block
}
Scala if statement contains an if keyword followed by a boolean expression.
If the boolean expression evaluates to true, then the statements inside the if block are executed. If the boolean expression evaluates to false, the statements inside the if block are not executed. After executing the if block, the program control continues with the statements after the if block.
Following are some of the examples of boolean expression and their resulting value.
(8>6)true(true && true)true(9%2==1)true(4>8)false(true && false)false
Example 1 – Scala IF statement
In the following example, we have an if statement where it checks if a is an even number. If the condition evaluates to true, it prints a string.
example.scala
object IfExample {
def main(args: Array[String]) {
var a=24
if (a%2==0){
println(a+" is an even number");
}
}
}
Output
24 is an even number
If a contains an odd number, the condition is false and the println statement is skipped.
Scala IF-ELSE Statement
The syntax of Scala if-else statement is
if(boolean_expression) {
// statements inside if block
} else {
// statements inside else block
}
Scala if-else statement contains a boolean expression, if block, and else block.
If the boolean expression evaluates to true, then the statements inside the if block are executed. If the boolean expression evaluates to false, the statements inside the else block are executed.
Example 2 – Scala if-else statement
In this example, we have a boolean expression where it checks if a is an even number. If the condition evaluates to true, it prints a that the number is even, else it prints that the number is odd.
example.scala
object IfElseExample {
def main(args: Array[String]) {
var a=27
if (a%2==0){
println(a+" is an even number");
} else {
println(a+" is an odd number");
}
}
}
Output
27 is an odd number
You may change the value of a, and run this program to understand the working of if-else statement in Scala.
Scala ELSE-IF Statement
The syntax of Scala if-else-if statement is
if(boolean_expression_1) {
// statements
} else if(boolean_expression_2) {
// statements
} else if(boolean_expression_3) {
// statements
} else {
// statements inside else block
}
Scala else-if statement contains a boolean expression if and else-if blocks.
The program control first evaluates the boolean_expression_1. If the boolean_expression_1 evaluates to true, then the block of statements next to the expression is evaluated. If boolean_expression_1 evaluates to false, then boolean_expression_2 is evaluated. If it evaluates to true, then the statements in the block right after the expression are evaluated. And if boolean_expression_2 evaluates to false, it continues with the next boolean expression the if-else-if ladder.
When an expression evaluates to true, the corresponding block is executed and the program control jumps to the end of if-else-if ladder.
When no boolean expression in the if-else-if evaluates to true, the optional else block at the end gets evaluated.
Example 3 – Scala if-else-if statement
In this example, we have a series of boolean expressions where a number is checked for divisibility.
example.scala
object ElseIfExample {
def main(args: Array[String]) {
var a=27
if (a%2==0){
println(a+" is divisible by 2")
} else if(a%3 ==0){
println(a+" is divisible by 3")
} else if(a%4 ==0){
println(a+" is divisible by 4")
} else if(a%5 ==0){
println(a+" is divisible by 5")
}
}
}
Output
27 is divisible by 3
You may change the value of a, and run this program to understand the working of if-else-if statement in Scala.
The order of conditions matters in an if-else-if ladder. Scala stops checking as soon as it finds the first true condition. For example, a number divisible by both 2 and 4 matches the divisibility-by-2 branch first in the program above.
Using Scala if-else as an Expression
A Scala if-else expression returns the value produced by the selected branch. This often removes the need to declare a mutable variable and assign it inside separate blocks.
object IfExpressionExample {
def main(args: Array[String]): Unit = {
val temperature = 31
val message = if (temperature >= 30) {
"It is hot"
} else {
"The temperature is moderate"
}
println(message)
}
}
Output
It is hot
The final expression in each branch becomes that branch’s result. In this example, each branch returns a String, so Scala infers that message is a String.
Scala if-else on One Line
A short if-else expression can be written on one line. This is suitable when both outcomes are brief and the condition remains easy to read.
val number = 12
val result = if (number % 2 == 0) "even" else "odd"
println(result)
Output
even
Scala does not use the Java-style ternary operator condition ? value1 : value2. The one-line if-else expression provides the same result.
Scala 3 if-then-else Syntax
Scala 3 supports an indentation-based form that uses the then keyword. Braces are optional when indentation clearly defines the branches.
if condition then
expressionWhenTrue
else
expressionWhenFalse
@main def checkAge(): Unit =
val age = 20
if age >= 18 then
println("Adult")
else
println("Minor")
Output
Adult
The traditional brace-based syntax remains common in Scala code. Use the syntax required by your Scala version and follow one consistent style within a project.
Checking Multiple Conditions in Scala if
Use Boolean operators to combine conditions:
&&returns true when both conditions are true.||returns true when at least one condition is true.!reverses a Boolean value.
object MultipleConditionsExample {
def main(args: Array[String]): Unit = {
val age = 25
val hasTicket = true
if (age >= 18 && hasTicket) {
println("Entry allowed")
} else {
println("Entry denied")
}
}
}
Output
Entry allowed
The && and || operators use short-circuit evaluation. With &&, Scala does not evaluate the second condition when the first is false. With ||, it does not evaluate the second condition when the first is true.
Nested if-else Conditions in Scala
An if or if-else block can contain another conditional expression. This is called a nested if. It is useful when a second decision should be made only after the first condition succeeds.
object NestedIfExample {
def main(args: Array[String]): Unit = {
val number = 18
if (number > 0) {
if (number % 2 == 0) {
println("Positive even number")
} else {
println("Positive odd number")
}
} else {
println("Zero or negative number")
}
}
}
Output
Positive even number
Deeply nested conditions can become difficult to follow. When possible, combine related Boolean checks, extract a condition into a well-named method, or use pattern matching when the decision is based on several distinct cases.
Returning a Value from a Scala Method with if-else
Because if-else is an expression, it can be the final expression of a method. Scala then returns the selected branch value without an explicit return keyword.
def numberType(number: Int): String = {
if (number > 0) {
"positive"
} else if (number < 0) {
"negative"
} else {
"zero"
}
}
println(numberType(-8))
Output
negative
Common Scala if-else Mistakes
- Using
=instead of==: Use==to compare values. A single=is used in definitions and assignments. - Writing a non-Boolean condition: Scala requires an actual
Booleanexpression. An integer cannot be used directly as a condition. - Placing broad conditions first: In an
else-ifladder, an early broad condition may prevent a more specific later condition from being checked. - Returning unrelated branch types: An
if-elseexpression is easier to use when both branches produce compatible values. - Omitting
elsewhen assigning a result: When a value is required for every possible condition, include anelsebranch. - Adding unnecessary semicolons: Scala usually infers statement endings from line breaks, so semicolons are generally optional.
Scala if-else Questions
Is there an else-if condition in Scala?
Yes. Write it as else if with a space. You may add multiple else if branches, and Scala executes only the first branch whose condition evaluates to true.
Can Scala if-else return a value?
Yes. Scala treats if-else as an expression. The value of the selected branch can be assigned to a variable, passed to another method, or returned from a method.
How do you write a one-line if-else in Scala?
Use the form if (condition) valueWhenTrue else valueWhenFalse. For example, val label = if (score >= 50) "Pass" else "Fail".
How do you check multiple conditions in Scala?
Use && when all conditions must be true, || when at least one condition must be true, and ! to negate a condition. Parentheses can be added to make complex expressions clearer.
Does Scala 3 require the then keyword?
Scala 3 supports the indentation-based if condition then syntax. It also supports familiar conditional code styles used in existing Scala projects, so the appropriate form depends on the Scala version and project style.
Scala if-else Editorial QA Checklist
- Confirm that every
ifcondition evaluates to aBoolean. - Verify that each example output matches the branch selected by the sample value.
- Check that broad conditions do not appear before more specific conditions unintentionally.
- Confirm that value-producing
if-elseexamples include a result for every branch. - Verify that Scala 3 indentation examples align each
elsewith its correspondingif. - Check that syntax-only, executable code, and output blocks use the appropriate PrismJS classes.
TutorialKart.com