Beginner 7 min readKotlin 2.0
Kotlin If / Else โ Conditions and Expressions
Kotlin if/else works like other languages but with one bonus: it can be used as an expression to return a value.
What You Will Learn
- Basic if/else syntax
- else if for multiple conditions
- if as an expression (replaces ternary)
- Nested if statements
Basic if / else
Use if to check a condition. The block runs when the condition is true.
Basic if/else
kotlin
fun main() {
val score = 75
if (score >= 90) {
println("Excellent")
} else if (score >= 60) {
println("Good")
} else {
println("Keep practicing")
}
}Output
Good
75 is >= 60 but not >= 90, so the second branch executes.
Beginner Tip: Always cover the else case to handle unexpected values.
if as an Expression
Kotlin if can return a value โ no ternary operator needed.
if Expression
kotlin
fun main() {
val age = 20
val status = if (age >= 18) "Adult" else "Minor"
println(status)
val max = if (10 > 7) 10 else 7
println(max)
}Output
Adult
10
When used as an expression, if/else must have an else branch. The last expression in each branch is the returned value.
Best Practice: Use if as an expression instead of a ternary operator. It is more readable and Kotlin has no ternary ?:.
Nested if
You can nest if statements inside each other.
Nested if
kotlin
fun main() {
val x = 10
if (x > 0) {
if (x % 2 == 0) {
println("Positive even")
} else {
println("Positive odd")
}
}
}Output
Positive even
The outer if checks if x is positive. The inner if checks if it is even.
Practice Exercise
Exercisepredict output
What prints? val n = 5 val result = if (n % 2 == 0) "Even" else "Odd" println(result)
Quick Quiz
Quick Quiz
Kotlin has a ternary operator like condition ? a : b.
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review