javakotlinif-statementswitch-statementkotlin-when

What is the standard for choosing "when" vs "if/else" in Kotlin?


I'm making the transfer from Java to Kotlin, and learning about the varied differences between the Java switch and the Kotlin when statement.

My question is, do the differences change the standard for when you choose when over a series of if and else if blocks?

For example, in Java switch is generally more efficient than else-ifs when there are 5 or more cases, and roughly comparable otherwise. If-else is generally preferred when the statements are boolean. Is this similar in Kotlin? Are there other reasons that differ to Java that I should consider when writing my code - ie standards for readability etc.

I would appreciate answers or links to more in depth reading on the subject - I have struggled to find any sources that do a good cost-benefit analysis.


Solution

  • Kotlin benefits over java is concise syntax

    when has a better design. It is more concise and powerful than a traditional switch

    Also more readable related to if else:

    when is that it can be used without an argument. In such case it acts as a nicer if-else chain: the conditions are Boolean expressions. As always, the first branch that matches is chosen. Given that these are boolean expression, it means that the first condition that results True is chosen.

    when {
        number > 5 -> print("number is higher than five")
        text == "hello" -> print("number is low, but you can say hello")
    }
    

    The advantage is that a when expression is cleaner and easier to understand than a chain of if-else statements.