What if a tiny check could save your whole program from crashing unexpectedly?
Why Preconditions (require, check, error) in Kotlin? - Purpose & Use Cases
Imagine you write a program that takes user input for age and you want to make sure the age is not negative. Without preconditions, you have to write many if statements everywhere to check if the input is valid before using it.
Manually checking conditions everywhere makes your code long, hard to read, and easy to forget. If you miss a check, your program might crash or behave strangely later, making bugs hard to find.
Kotlin's preconditions like require, check, and error let you quickly and clearly state what must be true before your code runs. They stop the program early with helpful messages if something is wrong, keeping your code clean and safe.
if (age < 0) { throw IllegalArgumentException("Age cannot be negative") } // continue with age
require(age >= 0) { "Age cannot be negative" } // continue with age
This lets you catch problems early and write safer, easier-to-understand code that clearly states its rules.
When building a banking app, you can use require to ensure withdrawal amounts are positive before processing, preventing mistakes and protecting users.
Manual checks clutter code and risk missing errors.
Preconditions provide a simple way to enforce rules upfront.
They improve code safety and clarity by stopping errors early.