Inspectopedia Help

Expensive Assertions

Expensive Assertions

In Kotlin, assertions are not handled the same way as from the Java programming language. In particular, they're just implemented as a library call, and inside the library call the error is only thrown if assertions are enabled.

This means that the arguments to the assert call will always be evaluated. If you're doing any computation in the expression being asserted, that computation will unconditionally be performed whether or not assertions are turned on. This typically turns into wasted work in release builds.

This check looks for cases where the assertion condition is nontrivial, e.g. it is performing method calls or doing more work than simple comparisons on local variables or fields.

You can work around this by writing your own inline assert method instead:

@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER") inline fun assert(condition: () -> Boolean) { if (_Assertions.ENABLED && !condition()) { throw AssertionError() } }

In Android, because assertions are not enforced at runtime, instead use this:

inline fun assert(condition: () -> Boolean) { if (BuildConfig.DEBUG && !condition()) { throw AssertionError() } }

Issue id: ExpensiveAssertion

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for Android 2023.3, Qodana for JVM 2023.3

Plugin:

Android, 2022.3.1 Beta 2

Last modified: 13 July 2023