CodeGym /Courses /Kotlin SELF /Tuples: Pair and Triple

Tuples: Pair and Triple

Kotlin SELF
Level 10, Lesson 1
Available

1. How do you return multiple values from a function?

If you’re just starting to program, it’s very easy to think: “Well, if I need to return two values, I’ll just… return two values.” Alas, most languages (Kotlin included) usually require a function to return exactly one value.

For this case, programmers have a hack: return not “two values”, but one container that contains two values inside. And that’s exactly where Pair and Triple show up in Kotlin.

Imagine a box with a label: “Two items inside.” That’s Pair. And a box that says “Three items inside” is Triple. Kotlin provides these boxes out of the box (sorry for the pun), so you don’t reinvent the wheel and don’t glue data together into a string like "10,20".

Pair: a container of two values

Pair is a standard Kotlin type that stores exactly two related values. Related is the key word: values that logically go together. Not “cutlets and space rockets”, but something like “name and age”, “X coordinate and Y coordinate”, “response code and message text”.

Importantly, Pair does not impose meaning on the components. It doesn’t have fields x and y, it doesn’t have name and age. It only has the honest and slightly boring first and second. The meaning comes from context and variable names around it.

Create a Pair via Pair(a, b) and read it via first/second

The most straightforward way is to call the constructor Pair(...).

fun main() {
    val point = Pair(10, 20)

    println(point.first)   // 10
    println(point.second)  // 20
}

Here, point is a “point”, which means we’ve agreed that first is x, and second is y. Kotlin doesn’t know that. Kotlin simply stores “first” and “second”. The agreement is on your conscience.

A more realistic example: “value + explanation”

Sometimes it’s useful to store a number and a short text next to it—for example, “calculation result + a comment about what it even was”.

fun main() {
    val result = Pair(200, "OK")

    println("code=${result.first}")     // code=200
    println("message=${result.second}") // message=OK
}

Note: reading result.first says little about what’s stored there. So we usually either give the variable a more specific name or (in the next lecture) unpack it via destructuring. But today we honestly practice reading values via first/second.

3. Triple: a container of three values

Triple is the twin brother of Pair, except it has three values inside. This is convenient when there really are three pieces of data and they form one meaningful set. The classic example is RGB: red, green, blue.

Just like with Pair, the component names are boring but obvious: first, second, third. Kotlin is basically saying: “I only store it. Meaning is your job.”

Create a Triple and read it via first/second/third

fun main() {
    val rgb = Triple(255, 128, 0)

    println("r=${rgb.first}")   // r=255
    println("g=${rgb.second}")  // g=128
    println("b=${rgb.third}")   // b=0
}

Cheat sheet: how to read components

When your eyes get tired of first/second/third, it’s useful to keep a simple cheat sheet.

Type How many values it stores How to read components
Pair
2
first, second
Triple
3
first, second, third

4. Convenient creation: to and type inference

Now there will be a small bit of “Kotlin magic”, but don’t be afraid: the magic here is harmless.

Besides Pair(a, b) there is a super-popular notation:

val range = 1 to 10

It creates Pair(1, 10).

This form works because to is a function that Kotlin allows you to call in infix form: when the function name stands between two values. Kotlin describes the rules for infix calls (the function must have one parameter and a few more requirements) in separate documentation about infix notation.

a to b is a pair, not “special syntax”

It’s important to understand: to is not “a part of the language for pairs”, but an ordinary function (it’s just convenient to use it in infix form). Therefore a to b is exactly the creation of Pair(a, b).

Important: 1 to 10 is not the range 1..10

Very important: 1 to 10 is not the range 1..10. It’s just a pair of values where first = 1, second = 10.

fun main() {
    val fromTo = 1 to 10

    println("from=${fromTo.first}") // from=1
    println("to=${fromTo.second}")  // to=10
}

Make your variable names “speak”

The readability of Pair almost always depends on variable names. If you name a variable well, the code becomes noticeably friendlier.

fun main() {
    val minMax = 3 to 12

    println("min=${minMax.first}") // min=3
    println("max=${minMax.second}") // max=12
}

The notation a to b is so common that Kotlin directly uses it in documentation examples when you need to “combine pairs”.

What types are stored inside Pair/Triple

Now for an important point: Pair and Triple can store anything. Want an Int and a String? Sure. Want a String and a Boolean? That’s also fine. Kotlin will often infer the types on its own, as we’ve already gotten used to with variables.

That is, if you write val p = 10 to 20, Kotlin understands that this is Pair<Int, Int>. But today we’re not going deep into the details—that will be much later. For now it’s enough to understand the practice: the types inside the pair correspond to what you put in it.

Pair of different types

fun main() {
    val user = Pair("Ada", 36)

    println(user.first)   // Ada
    println(user.second)  // 36
}

Here, first is a string, and second is a number. Kotlin handles that just fine.

Triple only when it’s one meaning, not a “bag of stuff”

Just remember: Triple is not a bag for “whatever else to cram in”. If the three values don’t form a single idea, later you yourself will look at it like a riddle.

fun main() {
    val movie = Triple("Matrix", 1999, true)

    println(movie.first)  // Matrix
    println(movie.second) // 1999
    println(movie.third)  // true
}

Does it work? Yes. Is it readable? Barely. Because true is “what”? “Watched”? “Liked”? “The movie exists”? That’s why Pair/Triple should be used carefully.

5. Application: a “rough expense draft” in the console

To avoid leaving Pair and Triple in the world of abstract points and colors, let’s start developing a small educational console app. Let it be a super-minimal “expense tracking draft”: the user enters a category and an amount, and we print a clear confirmation.

Today our task is simple: learn to store one expense entry as a bundle “category + amount”. For this, Pair is perfect: two values, one meaning.

Create an “expense” as a Pair

fun main() {
    val expense = "food" to 250

    println("Category: ${expense.first}") // Category: food
    println("Amount: ${expense.second}")  // Amount: 250
}

Yes, food and 250 could have been stored in two variables. But the idea is this: sometimes it’s convenient to pass it around as a single object: “here is the expense as a whole”.

Read input and assemble a Pair

We already know readln() and toIntOrNull(). Let’s not complicate it: suppose the user enters the category on the first line and the amount on the second.

fun main() {
    print("Enter category: ")
    val category = readln().trim()

    print("Enter amount: ")
    val amountText = readln().trim()
    val amount = amountText.toInt()

    val expense = category to amount
    println("Saved: ${expense.first} -> ${expense.second}") // example: Saved: food -> 250
}

This isn’t “real” expense tracking yet, but as a learning step it’s great: we saw how Pair becomes a small “package” for related information.

When Pair/Triple are appropriate, and when it’s better to stop

Pair and Triple are like duct tape. Useful around the house, but if you built a spaceship out of nothing but duct tape, you probably missed something in the design.

Usually Pair/Triple are appropriate when the values are truly small, there are few of them, and you can quickly tell from context what first and second mean. For example, x to y for a coordinate, min to max for bounds, code to message for a result.

But if you catch yourself constantly thinking “so what is first?” and start writing comments like // first = category, second = amount, that’s a signal: maybe you need a more “named” result. But I’ll tell you how to do that properly about 10 levels later.

7. Typical mistakes when working with Pair and Triple

Mistake No. 1: mixing up the component order (first/second).
The most common problem is to mix up what’s in first and what’s in second. Especially when in different parts of the code you create similar pairs but “agree differently”: somewhere it’s (min, max), and somewhere it’s (max, min). This is not a compiler error—it’s a meaning error. Discipline helps: fix the order and keep it the same everywhere, and give variables names that suggest that order (minMax, fromTo, xToY).

Mistake No. 2: using Pair for unrelated data “because you can”.
Technically you can put anything into a Pair. But if the two values don’t form one meaning, reading it turns into a puzzle. A week later you’ll open the code and try to guess why val x = pair.first, and what x even is. Pair is not a “takeout box” for random leftovers.

Mistake No. 3: hoping that first means “the main thing”.
Sometimes beginners feel like first is “the main field”, and second is “additional”. Kotlin doesn’t think so. There is no main or secondary; there is only order. If the meaning requires “mainness”, you need to express that via variable names and code logic, not hope for the magic of the word first.

Mistake No. 4: Triple as a “bag of everything”.
Triple easily turns into mini-chaos: “and a name in there, and an age, and a flag, and… oops, there’s no fourth slot.” If you already feel that Triple doesn’t fit the real meaning, this is not a “bad Triple”—it’s a good signal that your data model is asking for a more normal shape. For now just remember this signal—we’ll come back to it in the future, when we have our own types.

Mistake No. 5: long chains like .first.first....
When you start seeing constructs like something.first.second, it means that somewhere you nested a Pair inside a Pair and built yourself a labyrinth. In that situation, it’s better to stop and unpack intermediate values into variables with normal names. Even if it’s two lines longer, it’s cheaper for your brain than solving a “nesting doll made of first’s”.

1
Task
Kotlin SELF, level 10, lesson 1
Locked
Coordinates on the map
Coordinates on the map
1
Task
Kotlin SELF, level 10, lesson 1
Locked
Route bounds
Route bounds
1
Task
Kotlin SELF, level 10, lesson 1
Locked
Dividing the loot
Dividing the loot
1
Task
Kotlin SELF, level 10, lesson 1
Locked
Rectangle Passport
Rectangle Passport
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION