W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

12/20/2021

Kotlin when Expression

 In this tutorial you will learn about the Kotlin when Expression and its application with practical example.

Kotlin when Expression

In Kotlin, when expression is considered as replacement of switch statement exists in other languages like C, C++, and Java. It is more concise yet powerful than switch statements.

Syntax:-

Using When as an Expression

In Kotlin, when can be used as an expression like the if and we can assign its result to a variable –

Example:-

Output:-

Multiple when branches into one

In Kotlin, multiple branches can be combined into one as comma separated. This is helpful when you need to run a common logic for multiple cases –

Example:-

Output:-

Checking given value is in a range or not using in operator

In Kotlin, range is indicated using the (..) operator. For example, you can create a range from 1 to 5 using 1..5. The in operator allows you to check if a value belongs to a range/collection –

Example:-

Output:-

Checking given variable is of certain type or not using is operator

In Kotlin, is and !is operator can be used to check whether a value is of a particular type in runtime.

Example:-

Output:-

No comments:

Post a Comment

Note: only a member of this blog may post a comment.