Kotlin Runtime: Check, Require and Assert

Jul 23, 2019

Runtime checks

  • require: check arguments. Throws an IllegalArgumentException if the value is false.
  • check: check states. Throws an IllegalStateException if the value is false.
  • assert: other usage like check results. Throws an AssertionError if the value is false and runtime assertions have been enabled on the JVM using the -ea JVM option.

require

Check arguments, throws an IllegalArgumentException if false.

fun save(age: Int) {    require(age >= 0) { "Age must be positive integer: $age" }    // save the data}

check

Check states, throws an IllegalStateException if false.

class Worker {    private var isRunning = false    fun run() {        check(isRunning == false) { "Working is already running" }    }}

assert

Check results, throws an AssertionError if false.

val name = getName()assert(name.isNullOrEmpty() == false) { "getName result is null or empty" }

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.