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.
Practice
require function in Kotlin?Solution
Step 1: Understand
requireusagerequireis used to check if the inputs to a function are valid before proceeding.Step 2: Differentiate from other preconditions
checkis for program state, anderrorstops the program immediately.requireis specifically for argument validation.Final Answer:
To check if function arguments meet certain conditions -> Option DQuick Check:
require = argument check [OK]
- Confusing require with check for program state
- Thinking error is for argument validation
- Assuming require stops program immediately
check in Kotlin to verify a condition with a lazy message?Solution
Step 1: Recall
checkfunction signaturechecktakes a Boolean condition and a lambda returning a message string if false.Step 2: Match syntax with options
check(value > 0) { "Value must be positive" } usescheck(condition) { "message" }which is correct Kotlin syntax.Final Answer:
check(value > 0) { "Value must be positive" } -> Option CQuick Check:
check syntax = condition + lambda message [OK]
- Passing message as second argument instead of lambda
- Using comma inside lambda incorrectly
- Omitting braces for message lambda
fun test(x: Int) {
require(x > 0) { "x must be positive" }
check(x < 10) { "x must be less than 10" }
println("x is valid: $x")
}
test(15)Solution
Step 1: Evaluate
Since 15 > 0,require(x > 0)requirepasses without exception.Step 2: Evaluate
15 is not less than 10, socheck(x < 10)checkthrowsIllegalStateExceptionwith message "x must be less than 10".Final Answer:
IllegalStateException: x must be less than 10 -> Option AQuick Check:
require passes, check fails with IllegalStateException [OK]
- Thinking require throws error for x=15
- Assuming println runs after failed check
- Confusing exception types thrown by require and check
fun validate(name: String) {
require(name.isNotEmpty(), "Name cannot be empty")
check(name.length > 3) { "Name too short" }
}Solution
Step 1: Review
Bothrequiresyntaxrequire(condition, "message")(eager message) andrequire(condition) { "message" }(lazy message) are valid overloads.Step 2: Review
The lambda syntax for check is also valid. The code compiles and works as expected.checksyntaxFinal Answer:
No error, code is correct -> Option BQuick Check:
Both eager and lazy messages valid [OK]
- Thinking comma message is invalid for require
- Confusing require syntax with only lambda support
- Forgetting that multiple overloads exist
fun criticalCheck(flag: Boolean) {
// Your code here
}Solution
Step 1: Understand
errorfunction purposeerrorimmediately throws anIllegalStateExceptionwith the given message and stops the program.Step 2: Apply
Useerrorfor critical failureif (!flag) error("Critical failure")to stop execution immediately when condition fails.Final Answer:
Useerror("Critical failure")if flag is false -> Option AQuick Check:
error stops program immediately with message [OK]
- Using require or check which throw exceptions but may be caught
- Printing message without stopping program
- Not stopping program on critical failure
Ready to prove it?
Pass the test and this pattern moves unknown
