Search code examples
kotlinswitch-statement

How to implement switch-case statement in Kotlin


How to implement equivalent of following Java switch statement code in Kotlin?

switch (5) {
    case 1:
    // Do code
    break;
    case 2:
    // Do code
    break;
    case 3:
    // Do code
    break;
}

Solution

  • You could do it like this:

    when (x) {
        1 -> print("x == 1")
        2 -> print("x == 2")
        else -> { // Note the block
            print("x is neither 1 nor 2")
        }
    }
    

    Extracted from official help.