Kotlin — Returning a value with when
Kotlin when can produce a value. It evaluates branches in order and returns the result of the first matching branch.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
fun main() {
val word = when (2) {
2 -> "two"
else -> "other"
}
println(word)
}
two
Classify a stock level
when is an expression. Each condition is evaluated in order until one matches, and else supplies the fallback. The resulting String initializes status.
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
Kotlin/JVM. Run these commands from the directory containing the example.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
fun main() {
val stock = 3
val status = when {
stock == 0 -> "sold out"
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.