Kotlin Conditions: if, else and when
Conditions let your program choose what to do based on a value.
if and else
Example
fun main() {
val marks = 45
if (marks >= 50) {
println("Pass")
} else {
println("Fail")
}
}Fail
The condition goes inside round brackets. The code inside the curly braces runs only when the condition is true.
else if
Use else if to check more than two cases. Kotlin checks them from top to bottom and stops at the first true one.
Example
fun main() {
val temperature = 38
if (temperature > 40) {
println("Very hot, stay indoors")
} else if (temperature > 30) {
println("Hot day in Karachi")
} else {
println("Pleasant weather")
}
}Hot day in Karachi
if as an Expression
In Kotlin, if can return a value. You can store the result directly in a variable. This is why Kotlin has no ? : ternary operator like Java.
Example
fun main() {
val marks = 72
val grade = if (marks >= 80) "A" else if (marks >= 60) "B" else "C"
println("Grade: $grade")
val a = 15
val b = 9
val bigger = if (a > b) a else b
println("Bigger number: $bigger")
}Grade: B Bigger number: 15
When if is used as an expression, the else part is required, so the variable always gets a value.
when
when is a cleaner way to write many else if branches. It compares a value with each branch and runs the first one that matches.
Example
fun main() {
val day = 6
val name = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6, 7 -> "Weekend"
else -> "Invalid day"
}
println(name)
}Weekend
6, 7 ->matches either value.elsehandles everything else, likedefaultin other languages.
when with Ranges and Conditions
A branch can check a range with in, or you can use when without a value and write full conditions:
Example
fun main() {
val marks = 85
when (marks) {
in 90..100 -> println("Excellent")
in 70..89 -> println("Good")
in 50..69 -> println("Average")
else -> println("Needs more practice")
}
val bill = 4500
val discount = when {
bill >= 5000 -> 10
bill >= 2000 -> 5
else -> 0
}
println("Discount: $discount%")
}Good Discount: 5%
| Branch form | Example |
|---|---|
| Exact value | 1 -> ... |
| Several values | 6, 7 -> ... |
| Range | in 70..89 -> ... |
| Type check | is String -> ... |
| Any condition (no subject) | bill >= 5000 -> ... |
Exercise
Exercise
What is printed? val x = 12 println(if (x % 2 == 0) "Even" else "Odd")
