Kotlin assert()

Kotlin assert()

In Kotlin, the assert() function is used for debugging purposes to check a given boolean expression and throw an AssertionError if the expression is false.

This function is often used during development to catch logical errors early in the program and ensure that certain conditions are met.

Note: AssertionError is thrown only if the runtime assertions have been enabled on the JVM using the -ea JVM option.

In this tutorial, we’ll explore the syntax of the assert() function and provide examples of its usage in Kotlin.

Syntax

The syntax of the assert() function is:

fun assert(value: Boolean): Unit

where

ParameterDescription
valueA boolean expression or value.
Parameter of assert() function

The assert() function takes a boolean expression as an argument. If the expression is false, an AssertionError is thrown.

Examples

1. Basic Usage of assert()

In this example, we’ll use assert() to check a condition and throw an AssertionError if the condition is not met.

Kotlin Program

fun main() {
    val x = 10
    val y = 20

    // Using assert to check a condition
    assert(x < y) { "Assertion failed: x is not less than y" }

    // Rest of the program
    println("Program continues after the assertion")
}

Output

Program continues after the assertion

In this example, the assert() function checks whether x < y is true. If the condition is false, it throws an AssertionError with the specified error message.

2. Enable JVM with runtime assertions and run assert()

In this example, we’ll use assert() to check a condition and throw an AssertionError if the condition is not met.

We are using IntelliJ IDEA, and to enable JVM to process runtime assertions,

1. Click on Run with Parameters…

2. Set VM options with -ea.

And click on Run.

Kotlin Program

fun main() {
    val x = 40
    val y = 20

    // Using assert to check a condition
    assert(x < y) { "Assertion failed: x is not less than y" }

    // Rest of the program
    println("Program continues after the assertion")
}

Output

Exception in thread "main" java.lang.AssertionError: Assertion failed: x is not less than y
	at MainKt.main(Main.kt:6)
	at MainKt.main(Main.kt)

Summary

In this tutorial, we’ve covered the assert() function in Kotlin, its syntax, and how to use it for checking boolean expressions during development. Using assert() helps catch potential issues early in the development process and ensures that certain conditions are met in your code.