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.
if(no1IsGreatest) no1 else if(no2IsGreatest) no2 else no3
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.
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.
object Main extends App {// create some numbersvar num1 = 100var num2 = 2var num3 = 200var num4 = 9000var num5 = 100000// check greaters between 3 numberscheckGreatest(num1, num2, num3)checkGreatest(num4, num2, num3)checkGreatest(num5, num4, num3)def checkGreatest(a:Int, b:Int, c:Int) ={var large = 0// perform ternary operationlarge = if (a > b && a > c) a else if(b > a && b > c) b else c// print largest numberprintf("Largest between %d, %d and %d is: %d\n", a , b, c, large)}}