ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

When Expression in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='82' AND `tutorial_status`=1 LIMIT 1

When Expression in Kotlin

📌 when Expression in Kotlin

In Kotlin, the when expression is a more powerful and flexible version of the traditional switch statement found in other languages. It is often used to replace multiple if-else-if statements for cleaner and more readable code.


✅ Syntax of when

kotlin

val number = 5when (number) { 1, 2, 3 -> println("Small Number") 4, 5, 6 -> println("Medium Number") else -> println("Large Number")}

Output:

mathematica

Medium Number


✅ 3. Using Ranges and Conditions

when supports range checks using the in and !in operators.

kotlin

val age = 25when (age) { in 0..12 -> println("Child") in 13..19 -> println("Teenager") in 20..59 -> println("Adult") else -> println("Senior")}

Output:

nginx

Adult


✅ 4. Using when Without an Argument

You can use when without an argument by using Boolean conditions.

kotlin

val number = 15when { number % 2 == 0 -> println("Even Number") number % 2 != 0 -> println("Odd Number") else -> println("Unknown")}

Output:

javascript

Odd Number


✅ 5. Using when as an Expression

when can return a value directly.

kotlin

val grade = 'B'val result = when (grade) { 'A' -> "Excellent" 'B' -> "Good" 'C' -> "Average" else -> "Fail"}println("Result: $result")

Output:

makefile

fun (obj: Any) { Unknown Type


✅ 7. Smart Casting in when

Kotlin performs smart casting inside when if it recognizes a type.

kotlin

fun (obj: Any) { when (obj) { is String -> println("Length: ${obj.length}") is Int -> println("Double Value: ${obj * 2}") else -> println("Unknown") }}describe("Hello")describe(7)

Output:

vbnet

Length: 5Double Value: 14


✅ Conclusion

  • when is more readable and powerful than traditional switch.

  • Supports multiple conditions, ranges, and type checking.

  • Can be used as an expression to return a value.

  • Eliminates the need for repetitive if-else statements.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql