Kotlin - When Expression

When Expression in Kotlin

The when expression in Kotlin is a powerful control flow construct that allows for more concise and readable code compared to traditional if-else chains or the switch statement in other languages. It can be used both as a statement and as an expression, making it versatile for various scenarios.

1. Basic Syntax

The basic syntax of the when expression is as follows:

when (expression) {
    value1 -> // code block
    value2 -> // code block
    else -> // code block
}

Here, the expression is evaluated, and its result is compared against the values specified in each branch. If a match is found, the corresponding code block is executed. The else branch is optional but recommended to handle unmatched cases.

2. Using when as an Expression

In Kotlin, when can return a value, making it usable as an expression:

val result = when (value) {
    1 -> "One"
    2 -> "Two"
    else -> "Other"
}

In this example, the variable result is assigned the string corresponding to the matched value.

3. Using when as a Statement

when can also be used as a statement when the result is not needed:

when (value) {
    1 -> println("One")
    2 -> println("Two")
    else -> println("Other")
}

Here, the appropriate message is printed based on the value.

4. Multiple Branch Conditions

You can combine multiple conditions in a single branch using commas:

when (value) {
    1, 2, 3 -> println("Value is between 1 and 3")
    else -> println("Value is outside 1 to 3")
}

This approach simplifies code when multiple values should trigger the same action.

5. Range and Collection Checks

when supports checking if a value is within a range or collection:

when (value) {
    in 1..10 -> println("Value is between 1 and 10")
    in validNumbers -> println("Value is valid")
    else -> println("Invalid value")
}

Using in and !in, you can check for inclusion or exclusion from ranges or collections.

6. Type Checks with is and !is

when can perform type checks using is and !is:

fun checkType(obj: Any) {
    when (obj) {
        is String -> println("It's a String of length ${obj.length}")
        is Int -> println("It's an Int: ${obj + 1}")
        else -> println("Unknown type")
    }
}

Kotlin's smart casting allows direct access to the object's properties after a successful type check.

7. when Without an Argument

Omitting the argument allows when to evaluate boolean expressions:

when {
    x.isOdd() -> println("x is odd")
    y.isEven() -> println("y is even")
    else -> println("x + y is odd")
}

This form is useful for complex condition evaluations.

8. Guard Conditions (Experimental Feature)

Guard conditions allow adding an if condition to a when branch:

when (animal) {
    is Animal.Cat if !animal.mouseHunter -> feedCat()
    else -> println("Unknown animal")
}

Note: Guard conditions are experimental and require enabling with the -Xwhen-guards compiler option.

9. Sealed Classes and Exhaustiveness

When using sealed classes, when can ensure all cases are covered without an else branch:

sealed class Result
data class Success(val data: String) : Result()
data class Error(val exception: Exception) : Result()

fun handle(result: Result) {
    when (result) {
        is Success -> println("Data: ${result.data}")
        is Error -> println("Error: ${result.exception.message}")
    }
}

The compiler checks for exhaustiveness, ensuring all subclasses are handled.

10. Smart Casting

After a successful type check, Kotlin smart casts the variable, allowing direct access to its properties:

fun process(obj: Any) {
    when (obj) {
        is String -> println("Length: ${obj.length}")
        is Int -> println("Incremented: ${obj + 1}")
        else -> println("Unknown type")
    }
}

This feature reduces the need for explicit casting.

11. when vs if-else

when provides a cleaner syntax for multiple conditions compared to nested if-else statements. It's especially useful when checking a variable against multiple values or types.

Kotlin's when expression is a versatile tool that enhances code readability and conciseness. Its ability to handle multiple conditions, type checks, and even act as an expression returning values makes it a preferred choice for control flow in Kotlin programming.

Beginner 5 Hours

When Expression in Kotlin

The when expression in Kotlin is a powerful control flow construct that allows for more concise and readable code compared to traditional if-else chains or the switch statement in other languages. It can be used both as a statement and as an expression, making it versatile for various scenarios.

1. Basic Syntax

The basic syntax of the when expression is as follows:

when (expression) { value1 -> // code block value2 -> // code block else -> // code block }

Here, the expression is evaluated, and its result is compared against the values specified in each branch. If a match is found, the corresponding code block is executed. The else branch is optional but recommended to handle unmatched cases.

2. Using when as an Expression

In Kotlin, when can return a value, making it usable as an expression:

val result = when (value) { 1 -> "One" 2 -> "Two" else -> "Other" }

In this example, the variable result is assigned the string corresponding to the matched value.

3. Using when as a Statement

when can also be used as a statement when the result is not needed:

when (value) { 1 -> println("One") 2 -> println("Two") else -> println("Other") }

Here, the appropriate message is printed based on the value.

4. Multiple Branch Conditions

You can combine multiple conditions in a single branch using commas:

when (value) { 1, 2, 3 -> println("Value is between 1 and 3") else -> println("Value is outside 1 to 3") }

This approach simplifies code when multiple values should trigger the same action.

5. Range and Collection Checks

when supports checking if a value is within a range or collection:

when (value) { in 1..10 -> println("Value is between 1 and 10") in validNumbers -> println("Value is valid") else -> println("Invalid value") }

Using in and !in, you can check for inclusion or exclusion from ranges or collections.

6. Type Checks with is and !is

when can perform type checks using is and !is:

fun checkType(obj: Any) { when (obj) { is String -> println("It's a String of length ${obj.length}") is Int -> println("It's an Int: ${obj + 1}") else -> println("Unknown type") } }

Kotlin's smart casting allows direct access to the object's properties after a successful type check.

7. when Without an Argument

Omitting the argument allows when to evaluate boolean expressions:

when { x.isOdd() -> println("x is odd") y.isEven() -> println("y is even") else -> println("x + y is odd") }

This form is useful for complex condition evaluations.

8. Guard Conditions (Experimental Feature)

Guard conditions allow adding an if condition to a when branch:

when (animal) { is Animal.Cat if !animal.mouseHunter -> feedCat() else -> println("Unknown animal") }

Note: Guard conditions are experimental and require enabling with the -Xwhen-guards compiler option.

9. Sealed Classes and Exhaustiveness

When using sealed classes, when can ensure all cases are covered without an else branch:

sealed class Result data class Success(val data: String) : Result() data class Error(val exception: Exception) : Result() fun handle(result: Result) { when (result) { is Success -> println("Data: ${result.data}") is Error -> println("Error: ${result.exception.message}") } }

The compiler checks for exhaustiveness, ensuring all subclasses are handled.

10. Smart Casting

After a successful type check, Kotlin smart casts the variable, allowing direct access to its properties:

fun process(obj: Any) { when (obj) { is String -> println("Length: ${obj.length}") is Int -> println("Incremented: ${obj + 1}") else -> println("Unknown type") } }

This feature reduces the need for explicit casting.

11. when vs if-else

when provides a cleaner syntax for multiple conditions compared to nested if-else statements. It's especially useful when checking a variable against multiple values or types.

Kotlin's when expression is a versatile tool that enhances code readability and conciseness. Its ability to handle multiple conditions, type checks, and even act as an expression returning values makes it a preferred choice for control flow in Kotlin programming.

Related Tutorials

Frequently Asked Questions for Kotlin

Companion objects hold static members, like Java’s static methods, in Kotlin classes.

A concise way to define anonymous functions using { parameters -> body } syntax.

Kotlin prevents null pointer exceptions using nullable (?) and non-null (!!) type syntax.

Inline functions reduce overhead by inserting function code directly at call site.

JetBrains, the makers of IntelliJ IDEA, developed Kotlin and released it in 2011.

Allows non-null variables to be initialized after declaration (used with var only).

val is immutable (read-only), var is mutable (can change value).

Compiler automatically determines variable types, reducing boilerplate code.

A data class automatically provides equals(), hashCode(), toString(), and copy() methods.

A function that takes functions as parameters or returns them.

Kotlin is a modern, statically typed language that runs on the Java Virtual Machine (JVM).

They add new methods to existing classes without modifying their source code.

It allows unpacking data class properties into separate variables.

== checks value equality; === checks reference (memory) equality.


apply is a scope function to configure an object and return it.

A class that restricts subclassing, useful for representing restricted class hierarchies.

Coroutines enable asynchronous programming by suspending and resuming tasks efficiently.

Functions can define default values for parameters, avoiding overloads.

Kotlin offers concise syntax, null safety, and modern features not found in Java.

Kotlin automatically casts variables to appropriate types after type checks.

Use the object keyword to create a singleton.

Calls a method only if the object is non-null.

Yes, Kotlin supports backend development using frameworks like Ktor and Spring Boot.

Data structures like List, Set, and Map, supporting functional operations.

line

Copyrights © 2024 letsupdateskills All rights reserved