Kotlin Bricks: When is better than If

One of my favorite things about Kotlin is the when expression. Its like a combination of an if and a switch you might be familiar with from Java. Performance is that of a standard if statement, , but it reads better and is more functional. Here is a quick example that handles specific values, ranges, and anything beyond.

val people = 10
when (people) {
    0 -> print("none")
    1 -> print("party of one")
    2 -> print("a couple")
    3, 4, 5 -> print("a few")
    in 6..12 -> print("a group")
    in 13..50 -> print("a gathering")
    else -> print("way too many")
}

My favorite ways to use when is to have it return a value based on a condition. Here is an example where I get a string based on the value of an enum.

val message = when (status) {
    Status.ONLINE -> R.string.connected
    Status.OFFLINE -> R.string.offline
    Status.CHECKING -> R.string.checking
    else -> R.string.unknown
}

Another way to use when is more like an if else statement. I generally don't use there because it can lead to comprehension issues. Here is an example where a mammal weighing more than 300 it would never reach the print statement, even though you might expect it to.

when {
    animal.isMammal() -> growHair()
    animal.isBird() -> {
        fly()
        makeNest()
        layEgg()
    }
    animal.weight > 300 -> print("make way")
}