Scala — Choosing a value with if
In Scala, if and else form an expression. Its result can be assigned to a val, so each condition selects a value for the same immutable binding.
A simple example
Choose one value
- Start with n is 2
- Do this Choose by sign
- Result positive
object Lesson extends App {
val n = 2
val word = if (n > 0) "positive" else "other"
println(word)
}
positive
Classify a stock level
An if/else expression returns a value, so there is no separate mutable status variable. The zero case comes first because zero also satisfies the low-stock threshold.
A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.
Run the example
Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
def main(args: Array[String]): Unit = {
val stock = 3
val status =
if (stock == 0) "sold out"
else if (stock <= 5) "order soon"
else "in stock"
println(status)
}
}
order soon
The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.
Try it yourself
Try the boundary values 0, 5, and 6.
Check your answer
They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.