</>
Skip to content
Kotlin lessons (12/33)

Kotlin — If Else

Basic if

fun main() {
    val temperature = 28

    if (temperature > 25) {
        println("It's warm!")
    }
}

if as expression

fun main() {
    val x = 10
    val label = if (x > 5) "big" else "small"
    println(label) // big
}

if-else if-else

fun main() {
    val score = 85

    val grade = if (score >= 90) "A"
    else if (score >= 80) "B"
    else if (score >= 70) "C"
    else "F"

    println(grade) // B
}

when expression

fun main() {
    val day = 3

    val name = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        4 -> "Thursday"
        5 -> "Friday"
        6, 7 -> "Weekend"
        else -> "Invalid"
    }

    println(name) // Wednesday
}

when with ranges

fun main() {
    val score = 85

    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89 -> "B"
        in 70..79 -> "C"
        in 60..69 -> "D"
        else -> "F"
    }

    println(grade) // B
}

when with type checking

fun main() {
    val obj: Any = "hello"

    when (obj) {
        is Int -> println("Int: $obj")
        is String -> println("String: $obj")
        is List<*> -> println("List of size ${obj.size}")
        else -> println("Other")
    }
}

Nested conditions

fun main() {
    val age = 25
    val hasTicket = true

    if (age >= 18) {
        if (hasTicket) {
            println("Welcome!")
        } else {
            println("Need a ticket")
        }
    } else {
        println("Must be 18+")
    }
}

Mini Practice

Write Kotlin code that:

  1. Uses if as an expression to assign a value
  2. Uses when with ranges to classify a score
  3. Uses when with type checking
  4. Combines conditions with && and ||

Up Next

In the next lesson, you'll learn about Loops — for, while, and iteration in Kotlin.

Related Topics

Frequently Asked Questions about If Else

What is If Else in Kotlin?

If Else is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn If Else?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn If Else.

Why is If Else important in Kotlin?

If Else is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.