Home
Search
Scala If, Else ExampleUse an if, else if and else construct to test values. See the match case if syntax.
If, else. 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.
An expression. In Scala 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.
First example. 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.
Println
Result The program prints "Not 20 or 30" because the number is 10. The if and else-if conditions do not evaluate to true.
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
Expression result. 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.
Here The size is set to 20 if the animal is "bird." Otherwise size is set to 10.
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
If versus match. 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.
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
If inside match. 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.
Tip With guarded cases, we can use more complex expressions to test inside a match. We combine if-statements with pattern matching.
// 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) } // Call def. printMessage(1) printMessage(-50)
Important, code is 1 Not important, code is -50
Match, continued. An 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.
Match
A summary. 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.
Home
© 2007-2022 sam allen.
see site info on the changelog.