March 4, 2023

Auto Casting in Kotlin Using When Expression: How It Works

Discover how to use Kotlin's when expression with auto casting to simplify your code. Learn how it works and increase your Kotlin programming efficiency

In Kotlin, the when expression can be used to check a value against multiple conditions and perform different actions based on the matching condition. When used in combination with smart casts, the when expression can automatically cast a value to a specific type.

Here's an example:

fun processString(input: Any) {
    when (input) {
        is String -> println(input.length)
        is Int -> println(input * 2)
        is Double -> println(input / 2)

In this example, the processString() function takes an input of type Any, which means it can accept any type of value. Inside the when expression, the input is checked against three different conditions using the is operator. If the input is a String, the length of the string is printed. If the input is an Int, it is multiplied by 2 and printed. If the input is a Double, it is divided by 2 and printed.

The key here is that Kotlin is able to automatically cast the input to the appropriate type based on the matching condition in the when expression. So if the input is a String, it is automatically cast to a String type when the println(input.length) statement is executed. This allows you to write more concise and readable code without having to manually cast values to different types.

Last edited on August 6, 2023 by Admin

Latest articles