Assertions

suggest change

Assertions and precondition checks allow developers to declare assumptions about program state, validate function arguments, and catch programmer errors early. Kotlin provides built-in precondition functions in its standard library that integrate directly with Kotlin's type system and smart casting, along with testing assertion frameworks.

Standard Library Preconditions

Kotlin provides dedicated standard library functions for validation instead of manual if (...) throw ... boilerplate.

require and requireNotNull (Argument Validation)

Use require and requireNotNull to validate inputs passed by callers. If the condition is false, they throw an IllegalArgumentException:

fun setAge(age: Int) {
    require(age >= 0) { "Age must not be negative: $age" }
}

fun processUser(userId: String?) {
    // Throws IllegalArgumentException if null; smart-casts userId to String
    val id = requireNotNull(userId) { "userId must not be null" }

    println("Processing user $id (length: ${id.length})")
}

check and checkNotNull (State Validation)

Use check and checkNotNull when verifying the internal state of an object or component. If the check fails, they throw an IllegalStateException:

class ConnectionPool {
    private var isConnected = false
    private var sessionToken: String? = null

    fun query(sql: String) {
        check(isConnected) { "Cannot run query: ConnectionPool is not connected." }

        val token = checkNotNull(sessionToken) { "Active session token missing." }
        println("Executing '$sql' with token $token")
    }
}

Smart Casting via Contracts

A major advantage of requireNotNull and checkNotNull is that Kotlin's compiler contracts recognize them. Once validated, the compiler automatically smart-casts nullable types to non-null types:

fun printUpper(str: String?) {
    requireNotNull(str)
    // str is now smart-cast to non-null String; no ?. or !! required:
    println(str.uppercase())
}

error() for Unreachable Code

Use error() to immediately throw an IllegalStateException with a message when execution reaches a state that should be impossible:

sealed class State {
    object Idle : State()
    object Running : State()
    object Finished : State()
}

fun parseState(name: String): State = when (name) {
    "idle" -> State.Idle
    "running" -> State.Running
    "finished" -> State.Finished
    else -> error("Unknown state: $name")
}

JVM-Level Assertions (assert)

Kotlin supports the JVM assert keyword through the assert(condition) { message } function. If the condition evaluates to false, an AssertionError is thrown:

fun calculateSpeed(distance: Double, time: Double): Double {
    assert(time > 0.0) { "Time must be positive, but was $time" }
    return distance / time
}

[!NOTE] JVM assertions are disabled by default at runtime. They must be explicitly enabled using the -ea (enable assertions) JVM flag:

java -ea -jar app.jar

Use assert for internal invariant verification during development and debugging, but use require or check for production argument and state validation.

Unit Test Assertions (kotlin.test)

Kotlin includes a multiplatform test library kotlin.test that works across JVM, JS, and Native:

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertFailsWith

class MathTest {

    @Test
    fun testOperations() {
        val sum = 2 + 2
        assertEquals(4, sum, "Sum should equal 4")

        val list = listOf("apple", "banana")
        assertTrue("banana" in list)
    }

    @Test
    fun testExpectedExceptions() {
        // Assert that a specific exception is thrown
        val exception = assertFailsWith<IllegalArgumentException> {
            require(false) { "Expected failure" }
        }
        assertEquals("Expected failure", exception.message)
    }
}

Summary Comparison

Function Failure Exception Intended Purpose Active in Production?
require(cond) IllegalArgumentException Function parameter validation Yes
requireNotNull(val) IllegalArgumentException Parameter nullability check + smart cast Yes
check(cond) IllegalStateException Internal object/system state check Yes
checkNotNull(val) IllegalStateException State nullability check + smart cast Yes
assert(cond) AssertionError Invariant checks during dev/testing Only when -ea is passed
error(msg) IllegalStateException Unreachable or unhandled branches Yes

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents