Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 653
gil.fernandes Avatar asked Jul 16 '17 17:07

gil.fernandes


2 Answers

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.

like image 109
holi-java Avatar answered Nov 08 '22 23:11

holi-java


I use assert() and require() from the stdlib.

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

like image 38
voddan Avatar answered Nov 08 '22 21:11

voddan