[Solved] Kotlin assert() not working in IntelliJ IDEA

Kotlin assert() not working in IntelliJ IDEA

To make assert() work, you have to enable the runtime assertions in JVM.

To enable runtime assertions for JVM in IntelliJ IDEA,

1. Click on Run with Parameters…

IntelliJ IDEA, Run with Parameters...

2. Set VM options with -ea.

VM options

Now, you may run your Kotlin program.

The following is a sample Kotlin program, where we use an assert() statement, and the values are taken such that it throws AssertionError. Since, we have enabled runtime assertions on JVM, the AssertionError is shown in the output.

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)