Lesson contents

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

  1. Start with Value 2
  2. Do this Match case 2
  3. Result two
The matching case supplies the word. A different value can take the default path.
Lesson.kt
fun main() {
    val word = when (2) {
        2 -> "two"
        else -> "other"
    }
    println(word)
}
Output
two
Advertisements

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.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

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
Lesson.kt
fun main() {
    val stock = 3
    val status = when {
        stock == 0 -> "sold out"
        stock <= 5 -> "order soon"
        else -> "in stock"
    }
    println(status)
}
Output
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.

Kotlin language documentation

Related tags

  • Kotlin
  • conditions
  • branching
  • comparison