October 4, 2025

Scala – Conditional Statements

In this chapter, you will learn how to use conditional statements. We would cover the following conditional statements:

  1. if Statement
  2. if-else Statement
  3. Multiple if-else Statement
  4. Nested if-else Statement

 

1. if Statement

The if statement is use to evaluate a conditional expression and has the syntax:

if(expression) {
   // Execute if true
}

If the expression evaluates to true, then the code inside the block is executed. Otherwise, the code is skipped.

An example program is given below. Try to enter and run it using your compiler.

object ConditionDemo {
   def main(args: Array[String]) {
      var age = 10;

      if( age < 15 ){
         println("He is young");
      }
   }
}

 

2. if-else Statement

For the if-else statement, we have a conditional expression, then we have two blocks of code:

  • if block – executes if the expression evaluates to true
  • else block – executes if the expression evaluates to false

The code below is an example of how the if-else statement works

object ConditionDemo {
   def main(args: Array[String]) {
      var age = 10;

      if( age < 15 ){
         println("He is a child");
      }
      else {
         println("He is an adult");
      }

   }
}

 

3. Multiple if-else Statement

In this case, an if statement is followed by one or more else-if-else. This is used to test a series of possible conditions using one statement. An example would be assigning the grades of students based on their scores e.g 70 – 100 is A, 60 – 69 is B etc.

Also note that if one of the if statements evaluates to true, then the remaining statements are skipped.

object ConditionDemo {
  def main(args: Array[String]) {
    var score = 50;

    if( score == 70 ){
      println("Excellent!");
    } 
    else if( score > 49 ){
      println("Average performance");
    } 
    else if( score > 30 ){
      println("Not so good");
    } 
    else{
      println("He Failed!!");
    }
  }
}

In this example, the compiler starts by checking the first conditional expression (score == 70), then subsequently checks other expression if the result of the previous is false. So the output would be “Average Performance”. At this point, subsequent expressions are skipped.

 

4. Nested if-else Statement

In this case we would have if-else statements nested within another if-else statement. Here, each of the if blocks is treated separately.

object NestedDemo {
   def main(args: Array[String]) {
      var a = 100;
      var b = 200;
      
      if( a == 100 ){
         if( b == 200 ){
            println("A = 100 and B = 200");
         }
      }
   }
}

Leave a Reply