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.
From the Kotlin Coding Conventions:
Prefer using if for binary conditions instead of when. Prefer using when if there are three or more options.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With