Switch case Kotlin

6

In Java I use switch in several situations, as in the example below :

public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

How would that be in Kotlin, what is the equivalent statement?

    
asked by anonymous 18.08.2017 / 20:49

2 answers

7

Kotlin works with a different flow control, called when .

Your code, using when , might be like this.

Obviously the code could be different, but I understand that your question is only about using switch .

fun main(args: Array<String>) {
    val month = 8

    val monthString = when(month) {
        1 -> "Janeiro"
        2 -> "February"
        3 -> "March"
        4 -> "April"
        5 -> "May"
        6 -> "June"
        7 -> "July"
        8 -> "August"
        9 -> "September"
        12 -> "October"
        11 -> "November"
        10 -> "December"
        else -> "Invalid month"      
    }

    println(monthString);
}

See it working here.

    
18.08.2017 / 20:55
6
val monthString = when (month) {
    1 -> "January"
    2 -> "February"
    3 -> "March"
    4 -> "April"
    5 -> "May"
    6 -> "June"
    7 -> "July"
    8 -> "August"
    9 -> "September"
    10 -> "October"
    11 -> "November"
    12 -> "December"
    else -> "Invalid month"
}

Actually even in Java I would do differently:

val monthString = if (month < 1 || month > 12) "Invalid month" else arrayOf("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")[month - 1]

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
18.08.2017 / 20:55