Kotlin standard library functions
The library provides a lot of useful functions for easier usage of the language and common programming tasks. We'll explore the contracts (preconditions) functions and the so-called standard functions.
Contracts
In the base Kotlin package, you can find several functions that can be used for runtime checking of data. They can be used for defining preconditions in functions. If you ever coded in Java then you probably wrote a not null precondition, with checking that an argument passed to a method is not null. The following methods are available, check
, checkNotNull
, require
, requireNotNull
and error
. Let’s show some examples of them.
Check
This function accepts a boolean condition and if it evaluates to false it will throw an IllegalStateException:
check(str.length > 5) { "Minimum length is 5" }
CheckNotNull
This function accepts a nullable argument, and, if it is null, throws an IllegalStateException. Otherwise, it returns the same argument as a non-nullable...