Learning Kotlin: return when

Note This is the 13th post in a multipart series. If you want to read more, see our series index.

Continuing our break from the Koans today and looking at another cool trick I learned using Kotlin this week, focusing on the when keyword we covered previously. Let’s start with a simple function to return the text for a value using when:

fun step1(number: Int): String {
    var result = ""
    when (number) {
        0 -> result = "Zero"
        1 -> result = "One"
        2 -> result = "Two"
    }
    return result
}

The next evolution is avoiding the variable and returning directly (this is something I’d often do in .NET):

fun step2(number: Int): String {
    when (number) {
        0 -> return "Zero"
        1 -> return "One"
        2 -> return "Two"
    }
    return ""
}

And now we get to the cool part: returning the when directly:

fun step3(number: Int): String {
    return when (number) {
        0 -> "Zero"
        1 -> "One"
        2 -> "Two"
        else -> ""
    }
}

Yup, the when can return a value, which also lets us do one final trick:

fun step4(number: Int): String = when (number) {
    0 -> "Zero"
    1 -> "One"
    2 -> "Two"
    else -> ""
}

It’s so cool that your logic can just return from a condition—and it works with if statements too, even with the Elvis operator we learned yesterday:

fun ifDemo3(name: String?) = name ?: "Mysterious Stranger"