0
0
Kotlinprogramming~5 mins

When with ranges and types in Kotlin

Choose your learning style9 modes available
Introduction

The when expression helps you choose actions based on different values or types. Using ranges and types makes it easy to check if a value fits in a group or is a certain kind.

You want to check if a number falls within a certain range, like age groups.
You want to perform different actions depending on the type of an object, like String or Int.
You want to replace multiple <code>if-else</code> statements with cleaner code.
You want to handle different cases clearly and readably in your program.
Syntax
Kotlin
when (variable) {
    in range -> // code for values in the range
    !in range -> // code for values not in the range
    is Type -> // code for values of a certain type
    else -> // default code
}

in checks if a value is inside a range.

is checks if a value is of a certain type.

Examples
This checks if x is between 1 and 10.
Kotlin
val x = 5
when (x) {
    in 1..10 -> println("x is between 1 and 10")
    else -> println("x is outside 1 to 10")
}
This checks the type of obj and prints a message.
Kotlin
val obj: Any = "Hello"
when (obj) {
    is String -> println("It's a String")
    is Int -> println("It's an Int")
    else -> println("Unknown type")
}
This checks if y is NOT in the range 1 to 10.
Kotlin
val y = 15
when (y) {
    !in 1..10 -> println("y is not between 1 and 10")
    else -> println("y is between 1 and 10")
}
Sample Program

This program uses when to check if a value is in a range or of a certain type, then returns a message.

Kotlin
fun describe(value: Any): String {
    return when (value) {
        is String -> "It's a String of length ${value.length}"
        is Double -> "It's a Double with value $value"
        in 1..10 -> "Number is between 1 and 10"
        !in 11..20 -> "Number is not between 11 and 20"
        else -> "Unknown value"
    }
}

fun main() {
    println(describe(5))
    println(describe(25))
    println(describe("Kotlin"))
    println(describe(3.14))
    println(describe(true))
}
OutputSuccess
Important Notes

Ranges use .. to include both ends, like 1..10 means 1 to 10.

Use !in to check if a value is NOT in a range.

Type checks with is let you safely use the value as that type inside the block.

Summary

when can check if a value is inside or outside a range using in and !in.

You can check the type of a value using is inside when.

This makes your code easier to read and understand by grouping cases clearly.