Library contents

Kotlin require

A ticket order requires at least one seat. Reject invalid arguments before updating availability.

A simple example

require

  1. Start with A function needs a positive count
  2. Do this Supply 0
  3. Result Argument rejected
Zero violates the stated input rule before the calculation starts.

Syntax

Kotlin syntax
require(quantity > 0) { "Quantity must be positive" }
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

Reject an empty ticket order

A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.

From the programval quantity = 0
ResultCheck quantity
Lesson.kt

fun main() {
    val quantity = 0
    try {
        require(quantity > 0) { "Quantity must be positive" }
    } catch (invalid: IllegalArgumentException) {
        println("Check quantity")
    }
}
Output
Check quantity

Zero seats violates the precondition. The caller handles the validation failure by asking for a corrected quantity.

Advertisements

Accept a team entry

A team asks for four places at the Saturday session. The workshop accepts a positive number of places. Reject zero before saving the reservation.

Given4 places
Worked resultReservation accepted

Stop an empty reservation

A booking form sends zero places when the quantity field is cleared. The workshop accepts a positive number of places. Reject zero before saving the reservation.

Given0 places
Worked resultRequest a positive count

What to watch for

Catch only the failure you can recover from and preserve unrelated errors.

Documentation for require