Switch in Kotlin

Switch statements express conditionals across many branches in Kotlin.

Here’s a basic when (Kotlin’s switch equivalent):

fun main() {
    val i = 2
    print("Write $i as ")
    when (i) {
        1 -> println("one")
        2 -> println("two")
        3 -> println("three")
    }

    // You can use commas to separate multiple expressions in the same case statement.
    // We use the optional `else` case in this example as well.
    when(Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
        Calendar.SATURDAY, Calendar.SUNDAY -> println("It's the weekend")
        else -> println("It's a weekday")
    }
    
    // `when` without an argument is an alternate way to express if/else logic.
    // Here we also show how the `case` expressions can be non-constants.
    val t = Calendar.getInstance()
    when {
        t.get(Calendar.HOUR_OF_DAY) < 12 -> println("It's before noon")
        else -> println("It's after noon")
    }
    
    // A type `when` can be used to compare types instead of values.
    // This can be useful to discover the type of a variable. In this example, the
    // variable `i` will have the type corresponding to its clause.
    fun whatAmI(i: Any) {
        when (i) {
            is Boolean -> println("I'm a bool")
            is Int -> println("I'm an int")
            else -> println("Don't know type ${i::class.simpleName}")
        }
    }
    
    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")
}

To run the program, put the code in main.kt and use kotlin to execute it.

$ kotlinc main.kt -include-runtime -d main.jar
$ java -jar main.jar

The output will be:

Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type String

Now that we can run and build basic Kotlin programs, let’s learn more about the language.