Kotlin Tutorial menu

Kotlin Conditions: if, else and when

Conditions let your program choose what to do based on a value.

if and else

Example

kotlin
fun main() {
    val marks = 45
    if (marks >= 50) {
        println("Pass")
    } else {
        println("Fail")
    }
}
Output
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

kotlin
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")
    }
}
Output
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

kotlin
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")
}
Output
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

kotlin
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)
}
Output
Weekend
  • 6, 7 -> matches either value.
  • else handles everything else, like default in 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

kotlin
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%")
}
Output
Good
Discount: 5%
Branch formExample
Exact value1 -> ...
Several values6, 7 -> ...
Rangein 70..89 -> ...
Type checkis String -> ...
Any condition (no subject)bill >= 5000 -> ...

Exercise

Exercise

What is printed? val x = 12 println(if (x % 2 == 0) "Even" else "Odd")

Learn Kotlin with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp