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.

See Also  Learn Function Overloading & Polymorphism in Kotlin

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.

0 0 votes
Article Rating

Related articles

Mobile App Development Services

Mobile App Development - Android mobile application developer -...

15 Upbeat IDE for developing Android App

IDE for developing android Application abbreviated as Integrated development...

How to Enable WhatsApp Payment

WhatsApp Pay has finally been given regulatory approval by...

WhatsApp Payment Launch in Brazil

Facebook's WhatsApp messaging service rolled out a system across...

Case Studies

Compass Music Platform

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

NewsWeek Magazine

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

Beauty & Makeup Shop

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...
0
Would love your thoughts, please comment.x
()
x