How to get the largest numbers by a ternary operation in Scala

Overview

In Scala, there is no default ternary operator or operation because it's redundant to have such operations. In Scala, we use if-else and else-if conditional statements. We use this conditional statement for purposes such as finding the largest of three numbers. Let's look at how we can do that below.

Syntax

if(no1IsGreatest) no1 else if(no2IsGreatest) no2 else no3
Syntax to get largest of 3 numbers

Parameters

no1: This is the first number.

no2: This is the second number.

no3: This is the third number.

no1IsGreatest: This is to check if the first number no1 is the greatest of the three.

no2IsGreatest: this is to check if the second number no2 is the greatest of the three.

Return value

The value returned is no1 , no2, or no3. This is because when the no1IsGreatest condition returns true, no1 is the greatest. If the condition no2IsGreatest returns true , no2 is the greatest. If none of these conditions returns true, no3 is the greatest.

Example

object Main extends App {
// create some numbers
var num1 = 100
var num2 = 2
var num3 = 200
var num4 = 9000
var num5 = 100000
// check greaters between 3 numbers
checkGreatest(num1, num2, num3)
checkGreatest(num4, num2, num3)
checkGreatest(num5, num4, num3)
def checkGreatest(a:Int, b:Int, c:Int) ={
var large = 0
// perform ternary operation
large = if (a > b && a > c) a else if(b > a && b > c) b else c
// print largest number
printf("Largest between %d, %d and %d is: %d\n", a , b, c, large)
}
}

Explanation

  • Lines 3–7: We create some numbers.
  • Line 15: We create a function that takes three parameters. The parameters here represent the three numbers we want to find the greatest among them. It compares these numbers and prints the largest to the console.
  • Lines 10–12: We call the function we created to get the largest number.

Free Resources