Search code examples
kotlinpreconditions

Precondition functions in Kotlin - good practices


Being a newbie Kotlin coder, I wonder, if there are some good practices or even language constructs for declaring pre-conditions in functions.

In Java I have been using Guava's Preconditions checking utilities:

https://github.com/google/guava/wiki/PreconditionsExplained

After some further investigation I came across the require function:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/require.html

Is this what is generally used for checking preconditions on functions?


Solution

  • Of course. You can find all of the preconditions in Preconditions.kt. In addition to the require function, there are requireNotNull, check & checkNotNull functions.

    Since the documentation describes it poorly in Kotlin, but you can see the Objects#requireNonNull documentation in jdk as further.

    Checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors.