Skip to main content

Kotlin - Control Flow - when

Greetings!

Just like if, when also an expression. It has 2 forms.
  • With a value - behave as a switch operator.
  • Without a value - behave as if-else-if chain.

when as a switch

Java

private void dayOfWeek(int dayOfWeek) {
    switch (dayOfWeek) {
        case 1:
            System.out.println("Sunday");
            break;
        case 2:
            System.out.println("Monday");
            break;
        case 3:
            System.out.println("Tuesday");
            break;
        case 4:
            System.out.println("Wednesday");
            break;
        case 5:
            System.out.println("Thursday");
            break;
        case 6:
            System.out.println("Friday");
            break;
        case 7:
            System.out.println("Saturday");
            break;
        default:
            System.out.println("Invalid day");
    }
}

Kotlin

private fun dayOfWeek(dayOfWeek: Int) {
    when (dayOfWeek) {
        1 -> println("Sunday")
        2 -> println("Monday")
        3 -> println("Tuesday")
        4 -> println("Wednesday")
        5 -> println("Thursday")
        6 -> println("Friday")
        7 -> println("Saturday")
        else -> println("Invalid Day")
    }
}

How pretty is that?

Combine multiple branches

private fun whatDay(dayOfWeek: Int) {
    when (dayOfWeek) {
        2, 3, 4, 5, 6 -> println("Weekday")
        1, 7 -> println("Weekend")
        else -> println("Invalid Day")
    }
}

Using in operator

private fun examResult(marks: Int) {
    when (marks) {
        in 1..60 -> println("You failed")
        in 60..100 -> println("You passed")
        else -> println("Invalid number")
    }
}

when as an if-else-if

Java

private static void printType(int number) {
    if (number < 0) {
        System.out.println("Negative number");
    } else if (number % 2 == 0) {
        System.out.println("Even number");
    } else {
        System.out.println("Positive odd number");
    }
}

Kotlin

private fun printType(number: Int) {
    when {
        number < 0 -> println("Negative number")
        number % 2 == 0 -> println("Even number")
        else -> println("Positive odd number")
    }
}

when as an expression

We can return or assign the value of when expression.
private fun racer(speed: Int): String {
    return when {
        speed in 0..24 -> "Beginner"
        speed in 24..30 -> "Intermediate"
        speed in 30..41 -> "Average"
        speed > 41 -> "Pro"
        else -> "Invalid speed"
    }
}


Comments