Kotlin — If, else if, and else
An if chain in Kotlin tests Boolean conditions in order. Separate branches can perform an action for each outcome.
A simple example
Follow one branch
- Start with n is 2
- Do this Is n positive?
- Result yes
fun main() {
var n = 2
if (n > 0) {
println("yes")
} else {
println("no")
}
}
yes
Classify a stock request
Check whether a request is positive before comparing it with the available stock. Select one action for an invalid, fillable, or deferred request. Here each branch prints once. Ordering the invalid-request guard first prevents a nonpositive number from passing the stock comparison.
The equipment desk has three calculators to lend. A request for a negative quantity is invalid, three can be filled exactly, and eight must wait. Each request produces one decision.
Run the example
Use Kotlin 2.2 on the JVM. Run these commands from the directory containing the example.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
fun main() {
val available = 3
for (request in listOf(-1, 3, 8)) {
if (request <= 0) {
println("invalid")
} else if (request <= available) {
println("accept")
} else {
println("defer")
}
}
}
invalid accept defer
With three in stock, −1 is invalid, 3 can be filled exactly, and 8 must be deferred. Only the first matching branch runs.
Try it yourself
What should happen for a request of zero?
Check your answer
The first branch rejects it as invalid. Checking the stock limit first would incorrectly treat zero as fillable.