(+91) 113 551 1687 contact@syncsas.com New Delhi

When in Kotlin, Switch 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.

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.

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 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.Actually, with when you can substitute the most complex if/else you can have in your code.

when expression in Kotlin

For starters, you can use it as a regular switch. Imagine that, for example, you have a view and want to display a toast based on its visibility.

Actually, with when you can substitute the most complex if/else you can have in your code.