Kotlin if Expression
The if statement lets your program make decisions. Based on whether a condition is true or false, the program takes a different path. In Kotlin, if is also an expression — it can return a value, not just execute code.
Basic if Statement
val temperature = 35
if (temperature > 30) {
println("It is hot today.")
}If temperature > 30 is true, the block runs. If it is false, nothing happens.
if-else Statement
val marks = 45
if (marks >= 50) {
println("Passed")
} else {
println("Failed")
}if-else if-else Chain
val score = 72
if (score >= 90) {
println("Grade: A")
} else if (score >= 75) {
println("Grade: B")
} else if (score >= 60) {
println("Grade: C")
} else {
println("Grade: F")
}Output: Grade: C
How the Decision Tree Works
score = 72
│
score >= 90?
NO ↓
score >= 75?
NO ↓
score >= 60?
YES → print "Grade: C" ← stops here
if as an Expression (Returns a Value)
In Kotlin, if can return a value. This makes it function like the ternary operator in other languages.
val a = 15
val b = 22
// Traditional approach
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// Kotlin expression approach
val max2 = if (a > b) a else b
println(max2) // 22Multi-Line if Expressions
When using if as an expression with multiple lines in each branch, the last expression in each block is the returned value:
val age = 20
val ticket = if (age >= 18) {
println("Adult verified.")
"Full price"
} else {
println("Child verified.")
"Half price"
}
println("Ticket: $ticket")Output:
Adult verified.
Ticket: Full priceNested if Statements
val isWeekend = true
val isRaining = false
if (isWeekend) {
if (isRaining) {
println("Stay home and watch a movie.")
} else {
println("Go for a walk in the park.")
}
} else {
println("Go to work.")
}if with Logical Operators
val salary = 80000
val experience = 5
if (salary > 50000 && experience >= 3) {
println("Eligible for senior role.")
} else {
println("Not eligible yet.")
}Practical Example: BMI Calculator
fun main() {
val weight = 70.0 // kg
val height = 1.75 // meters
val bmi = weight / (height * height)
val category = if (bmi < 18.5) {
"Underweight"
} else if (bmi < 25.0) {
"Normal weight"
} else if (bmi < 30.0) {
"Overweight"
} else {
"Obese"
}
println("BMI: ${"%.2f".format(bmi)}")
println("Category: $category")
}Output:
BMI: 22.86
Category: Normal weight