Search code examples
kotlintestingassert

Is it safe to use Check and Require in production code? - Kotlin


I read from multiple sources is that we should avoid using assert in production, as an exception will not be thrown if the -ea flag is not enabled on the JVM.

However, as far as my understanding goes, the same does not apply check and require, i.e. they will always throw an exception regardless of JVM flags or any related settings.

I just wanted to double check that it is safe to use check and require by asking here before shipping to production.


Solution

  • require and check are absolutely fine to use is production code, it throw a IllegalArgumentException in case of unexpected state, regardless of -ea.

    Moreover, it can be considered as a good practice to do so, since it makes input checks consistent, more readable and allows smart casting to not-null type (via kotlin contract).