Kotlin

require / check / requireNotNull

admin by @admin ADMIN
14m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Three contract-style assertions in the stdlib: `require` for inputs (throws `IllegalArgumentException`), `check` for state (throws `IllegalStateException`), `requireNotNull` returns the value smart-cast.
Kotlin
Raw
class Money(val cents: Int, val currency: String) {
    init {
        require(cents >= 0)        { "cents must be non-negative, got $cents" }
        require(currency.length == 3) { "currency must be ISO 4217 (got $currency)" }
    }
}

class Account {
    private var open = true
    private var balance = 0

    fun deposit(amount: Int) {
        check(open)               { "cannot deposit on closed account" }
        require(amount > 0)        { "deposit must be positive" }
        balance += amount
    }

    fun close() { open = false }
}

fun firstChar(s: String?): Char {
    val nonNull = requireNotNull(s) { "string must not be null" }
    // nonNull is smart-cast to String here
    return nonNull[0]
}

fun main() {
    try { Money(-5, "USD") } catch (e: Exception) { println(e.message) }
    println(firstChar("hello"))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.