Library contents

Kotlin check and IllegalStateException

check throws IllegalStateException when an order is already locked.

A simple example

check and IllegalStateException

  1. Start with A record marked closed
  2. Do this Try adding a new item
  3. Result Operation rejected
The same item could be added while the record was open. Its current state prevents the change.

Syntax

Kotlin 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.jar

Add 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.

ResultOrder is closed
Lesson.kt
fun main() {
    val paid = true
    val items = mutableListOf<String>()
    try {
        check(!paid) { "Order is closed" }
        items.add("Pastry")
    } catch (closed: IllegalStateException) {
        println(closed.message)
    }
}
Output
Order is closed

The paid flag blocks the edit before another pastry enters the kitchen order.

Advertisements

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.

GivenOpen draft
Worked resultChange accepted

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.

GivenFinalized manifest
Worked resultStart amendment

What to watch for

Use require for a caller's invalid argument and check for an invalid state.

Documentation for check and IllegalStateException