Life is full of decisions, and your code should be too. Kotlin's if/else works just like most languages, but with a cool twist โ it can return a value.
The basic if statement
Use if to run code only when a condition is true.
fun main() {
val age = 18
if (age >= 18) {
println("You can vote!")
}
}
Try it Yourself โ
if...else
Add an else branch to handle the case when the condition is false.
fun main() {
val age = 16
if (age >= 18) {
println("You can vote!")
} else {
println("Too young to vote.")
}
}
Try it Yourself โ
else if chains
Check multiple conditions by chaining else if.
fun main() {
val score = 85
if (score >= 90) {
println("A")
} else if (score >= 80) {
println("B")
} else if (score >= 70) {
println("C")
} else {
println("F")
}
}
Try it Yourself โ
if as an expression
Here's the Kotlin special โ if can return a value. No ternary operator needed.
fun main() {
val age = 20
val result = if (age >= 18) "Adult" else "Minor"
println(result)
}
The last expression in each branch becomes the return value. Clean and readable.
Try it Yourself โ