How to perform a ternary operation in Scala

Overview

Unlike Java and JavaScript, which use the ternary operator to perform a logical operation, Scala uses another method. Scala uses the if-else conditional statement to achieve this purpose.

Syntax

if(condition) expression1 else expression2
The syntax for the tenary operation in Scala

Parameters

condition: This is the specified condition, which returns true or false.

expression1: This is executed if the condition returns true.

expression2: This is executed if the condition returns false.

Example

object Main extends App {
var num1 = 100
var num2 = 2
var num3 = 200
var num4 = 9000
// set large to 0
var large = 0
// compare num1 and num2
large = if (num1 > num2) num1 else num2
printf("Largest between %d and %d number is: %d\n", num1 , num2, large)
// compare num3 and num4
large = if (num3 > num4) num3 else num4
printf("Largest between %d and %d number is: %d\n", num3 , num4, large)
}

Explanation

  • Lines 2-5: We create some integer variables and initialize them.
  • Line 8: We create a variable called large which holds the larger of two numbers.
  • Lines 11 and 16: We compare the values to see which is greater and then print the value to the console.

Free Resources