Debug Assert

Does Kotlin have a assert-like method that can only be included in debug builds?

There is a require method which is almost free in runtime. You can also use Java assert on JVM, but I do not think it is recommended to do so right now.

Do you have a use case to share?

Please search for previous topic.

I have a number of use cases. I’m not sure which one (or ones) would help the most. I can dig one up a bit later, but basically they all come down to the same thing. I want my program to tell me (the programmer) in debug immediately when something happens I didn’t expect (range checks etc.) and in release, I want the code to do some configured behavior (log, email, … ) and possibly do some kind of correction to keep the program running in a stable state or possibly tell the user something is wrong, depending on the importance of the user knowing about the issue. I’m aware I don’t want side effects in the test and almost always I just want the program to stop (see running, but there might be other ways that would work. I’m used to systems where I get a notification of the problem as the programmer and can choose to silence the problem temporarily and record the problem in the environment to review at the end.

Does that help?

Well, this one is easy to solve:

val debug  = System.getProperty("debug").toBoolean() //or something similar

fun myError(block: () -> String) = if(debug){
} else {

Just add similar code to your program and you can use it wherever you need. The real problem arises when people try to remove debug code from release version.

Hi @darksnake,
I don’t see a reason to declare block as a lambda, in your example block is always evaluated.

It can be replaced with fun myError(message: String), what do you think?

require looks like it throws an exception, not what I want. The assert looks like it exists regardless of build settings.

myError looks like it would be included in both release and debug.

I think I have my answer though. I can’t select what code to compile while compiling like I’m used to having. I would have to write my own pre-compile processing step and somehow integrate that into my build steps. Please correct me if I’m wrong. Thanks.

I can’t find any docs on the error function. Is that something that might only be included in debug builds?

Some references for you:

One way to achieve something like this would be

const val DEBUG_ENABLED = true
inline fun DEBUG(block: () -> Unit) {
    if(DEBUG_ENABLED) block()
inline fun RELEASE(block: () -> Unit) {
    if(!DEBUG_ENABLED) block() 

As far as I know the compiler should just optimize away the if condition and the unused debug/release code.

Yes, you can.
However this slows the compilation without any performance gain on JVM.
Dead code elimination is already implemented on JVM and popular Android minifiers.

You are right.