Kotlin When Expression

The Kotlin when expression is one of the most powerful and expressive control flow features in the Kotlin programming language. It is an advanced and flexible alternative to the traditional switch statement found in many other languages. Kotlin's when expression enhances code readability, safety, and conciseness, making it widely used in Android development, backend services, and general Kotlin applications.

This detailed guide explains the Kotlin when expression from basic to advanced levels, with real-world examples, practical use cases, tables, and FAQs.

What Is Kotlin When Expression?

The when expression in Kotlin is a conditional expression that evaluates a value against multiple conditions and executes the matching branch. Unlike a traditional switch statement, when can be used as both a statement and an expression, meaning it can return a value.

Why Kotlin Introduced When Expression

  • Replaces verbose switch statements
  • Supports ranges, types, and conditions
  • Improves readability and maintainability
  • Works as an expression returning values

Kotlin When Expression Syntax

when (value) { condition1 -> action1 condition2 -> action2 else -> defaultAction }

The when block checks each condition sequentially and executes the first matching branch.

Basic Example of Kotlin When Expression

val day = 3 when (day) { 1 -> println("Monday") 2 -> println("Tuesday") 3 -> println("Wednesday") 4 -> println("Thursday") 5 -> println("Friday") else -> println("Weekend") }

This example demonstrates how Kotlin when expression replaces a switch-case structure.

Kotlin When as an Expression (Returning a Value)

One of the most important features is that Kotlin when can return values.

val score = 85 val grade = when (score) { in 90..100 -> "A" in 75..89 -> "B" in 60..74 -> "C" else -> "Fail" } println(grade)

This makes Kotlin when expression extremely useful for assigning values based on conditions.

Kotlin When Without Argument

Kotlin allows using when without a subject. This is useful for complex conditional logic.

val age = 20 when { age < 13 -> println("Child") age in 13..19 -> println("Teenager") age >= 20 -> println("Adult") }

Using Multiple Conditions in Kotlin When

val number = 5 when (number) { 1, 3, 5, 7, 9 -> println("Odd number") 2, 4, 6, 8 -> println("Even number") else -> println("Unknown") }

Kotlin When with Ranges

Ranges are commonly used in real-world applications like grading systems.

val temperature = 35 when (temperature) { in -10..0 -> println("Freezing") in 1..20 -> println("Cold") in 21..30 -> println("Warm") else -> println("Hot") }

Kotlin When with Data Types

Kotlin when expression can check object types using is.

fun describe(obj: Any) { when (obj) { is Int -> println("Integer value") is String -> println("String value") is Double -> println("Double value") else -> println("Unknown type") } }

Real-World Use Cases of Kotlin When Expression

1. User Role Validation

val role = "ADMIN" val accessLevel = when (role) { "ADMIN" -> "Full Access" "EDITOR" -> "Edit Access" "VIEWER" -> "Read Only" else -> "No Access" }

2. Payment Status Handling

val paymentStatus = 2 val message = when (paymentStatus) { 0 -> "Payment Pending" 1 -> "Payment Successful" 2 -> "Payment Failed" else -> "Unknown Status" }

Kotlin When vs Switch Statement

Feature Kotlin When Switch Statement
Return value Yes No
Type checking Supported Not supported
Range support Yes No
Else mandatory Recommended Optional

Common Mistakes to Avoid

  • Forgetting else branch
  • Overusing when instead of polymorphism
  • Using complex logic inside branches

The Kotlin when expression is a powerful, readable, and flexible way to handle conditional logic. It replaces traditional switch statements while offering advanced features such as value returns, range checks, type checking, and condition-based execution. Mastering when expressions significantly improves Kotlin code quality and maintainability.

Frequently Asked Questions (FAQs)

1. Is Kotlin when an expression or a statement?

Kotlin when is both. It can execute logic like a statement or return a value like an expression.

2. Is else mandatory in Kotlin when?

Else is mandatory when the when expression is used to return a value and all cases are not covered.

3. Can Kotlin when replace if-else?

Yes, Kotlin when can completely replace complex if-else chains and improve readability.

4. Can we use conditions in Kotlin when?

Yes, when without an argument allows condition-based checks similar to if-else.

5. Is Kotlin when faster than switch?

Performance is similar, but Kotlin when offers better flexibility and safety.

line

Copyrights © 2024 letsupdateskills All rights reserved