If-else Statement in Kotlin with Super Powers

There are two kinds of innovation: new perspectives that changes how we look at things and pragmatic improvements that changes how we do things. Kotlin is full of these pragmatic improvements, getting its user a language that just feel good to use. One of the most useful improvement, especially if you come from Java, is the when construct.

The switch expression in Java, and especially in Java 6, are extremely limited. Apart from a very short amount of types, it can not be used for anything else.

But, however, when expressions in Kotlin can do everything you can do with a switch and much more. The more Kotlin code we write, the more we love it! Kotlin’s modern language features together with Android KTX made our Android code more concise, clear and pleasant. We (@FMuntenescu and @objcode) started the #31DaysOfKotlin series as a way of sharing some of our favorite Kotlin and Android KTX features and hopefully get more of you to like it as much as we do.

Actually, with when you can substitute the most complex if/else you can have in your code. These troubles vanish when we start using Kotlin extension functions. With this feature, you can glue new methods to an existing type without introducing inheritance. Although it’s important to say that you can only access public methods and fields (because extensions are resolved statically) but when making shortcuts and designing new interfaces to interact with the SDK, it really makes a difference.

A traditional switch is basically just a statement that can substitute a series of simple if/else that make basic checks. However it cannot replace all sort of if/else sequences but just those which compare a value with some constant. So, you can only use a switch to perform an action when one specific variable has a certain precise value.

Leave a Reply

Your email address will not be published. Required fields are marked *