Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin When


Certainly! The when expression in Kotlin is similar to a switch statement in other languages. It's used to perform conditional checks on a value and execute different blocks of code based on the value. Here's a simple explanation with an example:

Syntax

Example

when (value) {
pattern1 -> {
// Code block 1
}
pattern2 -> {
// Code block 2
}
...
else -> {
// Default code block
}
}

Example

Let's say we want to print the name of the day of the week based on the provided number:

fun main() {
val day = 3

val dayOfWeek = when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Invalid day" // Default case
}

println("Day of the week: $dayOfWeek")
}

OutPut

Day of the week: Tuesday

Using Expressions

when can also be used as an expression, allowing you to assign its result to a variable.

Example

val type = when (value) {
is String -> "String"
is Int -> "Int"
else -> "Unknown"
}

Combining Conditions

You can combine multiple conditions using commas , or ranges.

Example

val result = when (value) {
in 1..10 -> "Range from 1 to 10"
in 11..20 -> "Range from 11 to 20"
else -> "Outside the range"
}

Checking Multiple Values

You can check multiple values in a single branch using the in operator.

Example

val result = when (value) {
1, 3, 5 -> "Odd"
2, 4, 6 -> "Even"
else -> "Unknown"
}

Conclusion

The when expression in Kotlin provides a flexible and concise way to perform conditional checks based on the value of an expression. It's versatile and can handle various scenarios, making it a powerful tool for writing clean and readable code.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java