Kotlin

Pair, Triple, and to() Infix

admin by @admin ADMIN
2h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`Pair<A,B>` and `Triple<A,B,C>` are stdlib lightweight tuples. The `to` infix returns a Pair — used everywhere for map literals.
Kotlin
Raw
fun main() {
    // Pair construction
    val pair: Pair<String, Int> = "age" to 30
    println(pair.first)     // age
    println(pair.second)    // 30

    // Destructure with componentN
    val (key, value) = pair
    println("$key = $value")

    // The whole point: map literals
    val config: Map<String, Any> = mapOf(
        "host"    to "localhost",
        "port"    to 8080,
        "debug"   to true,
    )

    // Triple — for three-valued returns where you don't want a data class
    fun divmod(a: Int, b: Int): Triple<Int, Int, Boolean> =
        Triple(a / b, a % b, b != 0)

    val (q, r, ok) = divmod(17, 5)
    println("$q remainder $r (ok=$ok)")

    // ⚠️ For >3 values or anything meaningful, use a data class — Pair/Triple
    // have generic field names (.first/.second/.third) that don't document intent.
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.