Consider a number variable that has a value we set during program runtime. We must use an if, else
-if statement to test its value.
In Scala 3.3 an if-else
construct returns a value—the result of the expression. After the condition we specify the return value. No return statement is needed.
In this program, we assign the var
number to the value 10. We then use an if, else
-if statement. We use println
in the blocks.
else
-if conditions do not evaluate to true.object Program { def main(args: Array[String]): Unit = { var number = 10 // Test number if an if, else-if, else construct. if (number == 20) println(20) else if (number == 30) println(30) else println("Not 20 or 30") } }Not 20 or 30
An if
-statement in Scala returns a value. So we can assign a value to an if-else
expression. This returns the values specified after the conditions.
object Program { def main(args: Array[String]): Unit = { var animal = "bird" // Use an if-else expression. // ... This returns 20 or 10 based on the animal. val size = if (animal == "bird") 20 else 10 // Print result of if-else. println(size) } }20
Here we convert an if-else
expression into a match expression. The if-else
uses fewer characters and lines. But the match may be clearer and easier to add more cases to.
object Program { def main(args: Array[String]): Unit = { val x = 100 // Use if-statement to set value of y1 based on x. val y1 = if (x == 100) 20 else 30 // Use match to set value of y2 based on x. // ... Equivalent to above if-statement. val y2 = x match { case 100 => 20 case _ => 30 } // Print results. println(y1) println(y2) } }20 20
We can use guarded cases inside a match construct. These use an if
-expression as part of the case. We capture a variable ("c") to be used later in the case.
if
-statements with pattern matching.object Program { // Print a message based on Int argument. // ... Use if-statement inside cases to determine message. def printMessage(code: Int) = code match { case c if c > 0 => println("Important, code is " + c) case c if c <= 0 => println("Not important, code is " + c) } def main(args: Array[String]): Unit = { // Call def. printMessage(1) printMessage(-50) } }Important, code is 1 Not important, code is -50
Match
, continuedAn alternative to the if
-construct is match—this may be clearer in some cases. We think of match more like a traditional switch
in C-like languages.
In Scala we use if-else
statements in an expression context. This makes an if
-construct similar to a function. It has logic and returns values.