Kotlin check and IllegalStateException
check throws IllegalStateException when an order is already locked.
A simple example
check and IllegalStateException
- Start with A record marked closed
- Do this Try adding a new item
- Result Operation rejected
Syntax
check(!paid) { message }
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarAdd an item after checkout closes
A bakery sends a paid order to the kitchen and locks the ticket. If a second cashier tries to add a pastry, the register needs to explain why the order can no longer change.
fun main() {
val paid = true
val items = mutableListOf<String>()
try {
check(!paid) { "Order is closed" }
items.add("Pastry")
} catch (closed: IllegalStateException) {
println(closed.message)
}
}
Order is closed
The paid flag blocks the edit before another pastry enters the kitchen order.
Edit a draft outing
An organizer adds a stop while the trip is still a draft. Allow a change only while the booking is open. A closed booking requires a separate amendment.
Protect a printed manifest
The clerk tries to edit an outing after its manifest has been finalized. Allow a change only while the booking is open. A closed booking requires a separate amendment.
What to watch for
Use require for a caller's invalid argument and check for an invalid state.