SyntaxStudy
Sign Up
Kotlin Destructuring and Range Expressions
Kotlin Beginner 1 min read

Destructuring and Range Expressions

Kotlin supports destructuring declarations that unpack an object into multiple variables in a single statement. Data classes automatically generate the componentN() functions required for destructuring, making it natural to unpack pairs, triples, map entries, and custom data classes. Range expressions created with .. or until allow you to express sequences of values concisely. Ranges work with Int, Long, Char, and any Comparable type. They integrate with for loops, the in operator, and the step modifier. The downTo infix function creates a descending range, and step lets you skip values. Ranges are also used inside when expressions and with the contains operator, providing a readable way to check membership.
Example
data class Point(val x: Int, val y: Int)

fun main() {
    // Destructuring a data class
    val (x, y) = Point(3, 7)
    println("x=$x  y=$y")

    // Destructuring a map entry
    val scores = mapOf("Alice" to 95, "Bob" to 87)
    for ((name, score) in scores) {
        println("$name scored $score")
    }

    // Pair and Triple
    val (first, second) = Pair("Kotlin", 2011)
    println("$first launched in $second")

    // Closed range (inclusive on both ends)
    val range = 1..10
    println(5 in range)          // true
    println(11 in range)         // false

    // Half-open range
    for (i in 0 until 5) print("$i ")   // 0 1 2 3 4
    println()

    // Step and downTo
    for (i in 10 downTo 1 step 2) print("$i ")  // 10 8 6 4 2
    println()

    // Char range
    for (ch in 'a'..'e') print(ch)   // abcde
    println()

    // Range in when
    val age = 20
    val category = when (age) {
        in 0..12   -> "Child"
        in 13..17  -> "Teen"
        in 18..64  -> "Adult"
        else       -> "Senior"
    }
    println(category)   // Adult
}