9

I've created sample class to test assertions in Kotlin

class Assertion {
    fun sum(a: Int, b: Int): Int {
        assert(a > 0 && b > 0)
        return a + b
    }
}

fun main(args: Array<String>) {
    Assertion().sum(-1, 2)
}

and was using the following options but the program doesn't throw assert exception.

-ea:AssertionKt, -ea:Assertion and -ea:...

Maxim
  • 1,194
  • 11
  • 24

2 Answers2

9

To enable assertions in Kotlin, run the JVM with the -ea option, without any additional specifiers.

yole
  • 92,896
  • 20
  • 260
  • 197
  • 1
    clear. thx. I also found useful [thread](https://discuss.kotlinlang.org/t/java-like-assert-statement/2277) related to this topic – Maxim Jun 19 '18 at 08:45
  • @Maxim please, accept the answer if it solves your issue ;) – user2340612 Jun 19 '18 at 09:54
  • 4
    All of the answers on this topic are uniform in the sentence like "run the JVM with the `-ea` option", however I cannot find how to actually do that in Android Studio. Googling "kotlin android studio set jvm option" or similar yields no solution. EDIT: After a while of question rephrasing I found the solution, if anyone will be wondering the same [Where to add compiler options like -ea in IntelliJ IDEA?](https://stackoverflow.com/questions/18168257/where-to-add-compiler-options-like-ea-in-intellij-idea) – Bojan P. Jun 21 '19 at 09:30
  • `kotlinc -J-ea` from https://discuss.kotlinlang.org/t/how-do-i-use-asserts-in-kotlin-scripts/4110/3 – schemacs Jul 15 '21 at 06:39
5

In Kotlin, unlike Java, assertions can be enabled/disabled only on top-level, i.e. by specifying -ea option to JVM.

Behind the scenes, assert() in Kotlin is a function, defined in AssertionsJVM.kt file. ENABLED variable in the _Assertions object is used to determine if assertions are enabled.

@PublishedApi
internal object _Assertions {
    @JvmField @PublishedApi
    internal val ENABLED: Boolean = javaClass.desiredAssertionStatus()
}

The ENABLED variable is assign to true if assertions enabled for the _Assertions class.

As a consequence, to turn on asserts in Kotlin they have to be enabled in JVM for

  • all classes -ea
  • or one particular class -ea:kotlin._Assertions
Maxim
  • 1,194
  • 11
  • 24