Switch Case in Kotlin: Using ‘When’ as a Replacement with Examples

We have all learned Switch cases in other programming languages like Java and C++. A switch case integrates control flow in a programming language. However, in Kotlin, there is no Switch case. Instead, we use When. When is a flexible and easy alternative to Switch in Kotlin. The reason Kotlin replaced Switch with When is that, unlike Switch, When can be used both as a statement and as an expression. It also supports a wide range of conditions including ranges and types.

Switch Case in Kotlin: Using 'When' as a Replacement with Examples

Switch Case in Kotlin: Using ‘When’ as a Replacement with Examples

The basic syntax of the ‘when’ expression in Kotlin:

1. Code Example of using When in Kotlin:

In this example, we are integrating When as a replacement for Switch in Kotlin. We are creating a system where users can pass the day name and it will tell us whether it is a weekend or a weekday.

2. Using Range with When in Kotlin:

In this example, we will be using different number ranges and if the given score is between these ranges it prints a message.

Thanks for reading our article, Happy Coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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