Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Assertions

You can make assertions using the assert() function, from the Kotlin standard library. This fulfils a similar purpose to Python’s assert statement, or C’s assert macro.

Here’s an example, with the equivalent code in Python & C provided for comparison:

fun processText(text: String) {
    assert(text.length > 0)
    ...
}
def process_text(text):
    assert len(text) > 0
    ...
#include <assert.h>
#include <string.h>

void process_text(const char* text)
{
  assert(strlen(text) > 0);
  ...
}

The example above looks very similar to the precondition functions that we saw earlier. We could easily replace the use of assert() with a call to require():

require(text.length > 0)

But these two approaches are subtly different.

require() is ‘always on’. It will always throw an IllegalArgumentException if its argument evaluates to false.

assert(), on the other hand, is ‘off by default’. It will do nothing unless assertions have been enabled on the JVM. If they are enabled, and its argument evaluates to false, then AssertionError will be thrown.

Thus require() is better suited to situations where run-time errors might be expected to occur from time to time, whereas assert() is better suited to situations where we are not expecting problems but want to have a ‘sanity check’ that can be enabled at run time when needed.

To enable assertions, it is necessary to pass the -ea command line option to the JVM. For example, if you have an application that has been compiled into a portable JAR file named app.jar, you would need to run it with either of these commands:

kotlin -J-ea app.jar
java -ea -jar app.jar

In Python and C, assertions are ‘on by default’, and need to be disabled manually. In Python, you would do this by running the python command with the -O command line argument. In C, you would do it by defining a special preprocessor symbol, NDEBUG, prior to the point where assert.h gets included into the source code.