Scala — If, else if, and else
Scala if can choose which action executes. A guard for invalid input should precede any broader condition that could otherwise accept it.
A simple example
Follow one branch
- Start with n is 2
- Do this Is n positive?
- Result yes
object Lesson extends App {
var n = 2
if (n > 0) {
println("yes")
} else {
println("no")
}
}
yes
Classify a stock request
Check whether a request is positive before comparing it with the available stock. Select one action for an invalid, fillable, or deferred request. These branches call println and produce Unit. A separate lesson uses the same conditional construct to compute and store a value.
The equipment desk has three calculators to lend. A request for a negative quantity is invalid, three can be filled exactly, and eight must wait. Each request produces one decision.
Run the example
Use Scala 2.13. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
def main(args: Array[String]): Unit = {
val available = 3
for (request <- List(-1, 3, 8)) {
if (request <= 0) {
println("invalid")
} else if (request <= available) {
println("accept")
} else {
println("defer")
}
}
}
}
invalid accept defer
With three in stock, −1 is invalid, 3 can be filled exactly, and 8 must be deferred. Only the first matching branch runs.
Try it yourself
What should happen for a request of zero?
Check your answer
The first branch rejects it as invalid. Checking the stock limit first would incorrectly treat zero as fillable.