Kotlin check()

Kotlin check()

The Kotlin check() function is used for enforcing a specific condition and throwing an IllegalStateException if the condition is not met.

Syntax

The syntax of Kotlin check() function is

fun check(value: Boolean): Unit

where

ParameterDescription
valueThe boolean value to be checked. If false, an exception is thrown.
Parameters of check() function

If given value is false, the check() function throws an IllegalStateException.

Example 1: Basic Usage of check() function

In this example, we shall use the check() function to enforce the condition that the input number must be positive.

Kotlin Program

fun printPositiveNumber(number: Int) {
    check(number > 0) { "Number must be positive" }
    println("The number is positive: $number")
}

fun main() {
    printPositiveNumber(5)
    printPositiveNumber(-3)
}

Output

The number is positive: 5
Exception in thread "main" java.lang.IllegalStateException: Number must be positive
	at MainKt.printPositiveNumber(Main.kt:2)
	at MainKt.main(Main.kt:8)
	at MainKt.main(Main.kt)

The first call to printPositiveNumber() with a positive number 5 prints the message The number is positive: 5.

The second call to printPositiveNumber() with a negative number -3 throws an IllegalStateException.

Example 2: Checking List Size using check() function

In this example, we shall use the check() function to ensure that a list has at least three elements before processing it.

Kotlin Program

fun processList(list: List<String>) {
    check(list.size >= 3) { "List must have at least three elements" }
    println("Processing the list: $list")
}

fun main() {
    val validList = listOf("Apple", "Banana", "Orange")
    val invalidList = listOf("Dog", "Cat")

    processList(validList)
    processList(invalidList)
}

Output

Processing the list: [Apple, Banana, Orange]
Exception in thread "main" java.lang.IllegalStateException: List must have at least three elements
	at MainKt.processList(Main.kt:2)
	at MainKt.main(Main.kt:11)
	at MainKt.main(Main.kt)

The first call to processList() with a valid list prints the message given in println().

The second call with an invalid list, containing only two elements, throws an IllegalStateException.

Summary

In this tutorial, we have learnt about Kotlin check() function, its styrax, and how to use this function for asserting conditions during runtime.

It is useful for validating inputs, enforcing preconditions, and catching potential issues early in the program’s execution.