kotlinbeginner

Destructuring Declarations

Destructure objects into variables: data classes, maps, pairs, and custom componentN operators.

kotlin
data class Color(val r: Int, val g: Int, val b: Int, val alpha: Float = 1.0f)

data class HttpResponse(
    val status: Int,
    val headers: Map<String, String>,
    val body: String
)

// Custom componentN
class DateRange(val start: String, val end: String, val days: Int) {
    operator fun component1() = start
    operator fun component2() = end
    operator fun component3() = days
}

fun parseUrl(url: String): Triple<String, String, String> {
    val regex = Regex("(https?)://([^/]+)(/.*)")
    val match = regex.find(url) ?: return Triple("", "", "")
    return Triple(match.groupValues[1], match.groupValues[2], match.groupValues[3])
}

fun main() {
    // Data class destructuring
    val color = Color(255, 128, 0)
    val (r, g, b) = color
    println("RGB: $r, $g, $b")

    // Skip components with _
    val (_, _, blue, alpha) = color
    println("Blue: $blue, Alpha: $alpha")

    // In loops
    val users = mapOf("alice" to 30, "bob" to 25, "charlie" to 35)
    for ((name, age) in users) {
        println("$name is $age years old")
    }

    // In lambdas
    val products = listOf(
        Pair("Laptop", 999.99),
        Pair("Mouse", 29.99),
        Pair("Keyboard", 79.99)
    )
    products
        .filter { (_, price) -> price > 50 }
        .forEach { (name, price) -> println("$name: \$$price") }

    // Triple
    val (protocol, host, path) = parseUrl("https://example.com/api/users")
    println("$protocol://$host$path")

    // HttpResponse
    val response = HttpResponse(200, mapOf("Content-Type" to "application/json"), "{\"ok\": true}")
    val (status, headers, body) = response
    println("$status: $body")

    // Custom componentN
    val range = DateRange("2024-01-01", "2024-12-31", 366)
    val (start, end, days) = range
    println("$start to $end ($days days)")

    // withIndex
    val items = listOf("a", "b", "c")
    for ((index, value) in items.withIndex()) {
        println("$index: $value")
    }

    // Regex destructuring
    val input = "John Doe, 42"
    val (fullName, ageStr) = input.split(", ")
    println("Name: $fullName, Age: $ageStr")
}

Use Cases

  • Clean variable extraction from complex objects
  • Map iteration with named components
  • Function return value decomposition

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.