Scala

22 / 52
   

Scala - Conditional Statements Examples

Conditional statements are controlled if if and else keywords.

if Statement
An if statement consists of a Boolean expression followed by one or more statements.

Syntax The syntax of an ‘if’ statement is as follows.

if(Boolean_expression) {
   // Statements will execute if the Boolean expression is true
}

Example:

object Hello {
   def main(args: Array[String]) {
      var x = 5;

      if( x < 10 ){
         println("If condition is true");
      }
   }
}

If-else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax The syntax of an if...else is ?

if(Boolean_expression){
   //Executes when the Boolean expression is true
} else{
   //Executes when the Boolean expression is false
}

Example:

object Hello {
   def main(args: Array[String]) {
      var x = 5;

      if( x < 10 ){
         println("If condition is true");
      } else {
         println("If condition is false");
      }
   }
}