0
0
Kotlinprogramming~5 mins

Preconditions (require, check, error) in Kotlin

Choose your learning style9 modes available
Introduction

Preconditions help you check if things are right before your program continues. They stop the program early if something is wrong.

When you want to make sure a function gets a valid input.
When you want to stop the program if a condition is not met.
When you want to give a clear message about what went wrong.
When you want to avoid bugs by catching errors early.
When you want to check assumptions in your code.
Syntax
Kotlin
require(condition) { "message" }
check(condition) { "message" }
error("message")

require is used to check arguments passed to a function.

check is used to check the state of the program.

Examples
This checks if the age is not negative before setting it.
Kotlin
fun setAge(age: Int) {
    require(age >= 0) { "Age must be non-negative" }
    println("Age set to $age")
}
This checks if the value is not zero before processing.
Kotlin
fun process(value: Int) {
    check(value != 0) { "Value must not be zero" }
    println("Processing $value")
}
This immediately stops the program with an error message.
Kotlin
fun failNow() {
    error("This function always fails")
}
Sample Program

This program tries to set an age. The first call works because 25 is valid. The second call fails because -5 is not allowed.

Kotlin
fun setAge(age: Int) {
    require(age >= 0) { "Age must be non-negative" }
    println("Age set to $age")
}

fun main() {
    setAge(25)  // This works
    setAge(-5)  // This causes an error
}
OutputSuccess
Important Notes

require throws IllegalArgumentException if the condition is false.

check throws IllegalStateException if the condition is false.

error throws IllegalStateException immediately with the message.

Summary

Use require to check function arguments.

Use check to check the program state.

Use error to stop the program with a message.