How do I use asserts in Kotlin scripts?


#1

I understand I need to enable runtime assertions on the JVM using the -ea JVM option. But how do I do that?


#2

You do it the same way that you do it for any JVM program. In intellij you edit your run configuration to add -ea to the command line parameters. Btw. it is also possible to enable assertions programmatically.


#3

What does it look like from the command line?

I know this doesn’t work: kotlinc -Jea -script Example.kts


#4

Assertions are enabled when running your program, not when compiling it. You need to pass it to the execution environment (kotlin), not the compiler (kotlinc).


#5

OK, but kotlinc is what I use to run the script. If I use kotlin it says running Kotlin scripts is not yet supported. I guess I will have to wait then?


#6

Kotlinc (and kotlin) is just a script that calls java. Looking at it, to pass arguments to the java command you have to prefix it with -J, but the processing just strips the first two characters (-J) and passes the rest to java. You’ll have to include the dash that Java sees. The following should work: kotlinc -J-ea -script Example.kts


#7

Ah that works. Thank you!