1. Pair/Triple and the result contract
To be honest, almost any useful real-life function is a bit “greedy”: it often wants to return not one value, but several at once. For example, you parse a string and want to return both the result and the string “tail”. Or you compute the minimum and maximum. Or you find coordinates and also compute something from them right away. And this is where a conflict appears: in Kotlin, a function always returns a single value.
But, as you can probably guess, there is no tragedy in this conflict: one returned value can be a container that holds multiple parts. Pair and Triple exist precisely to “bundle together” 2–3 values and return them as one payload.
Return a container, not “one number”
Previously you were used to the idea that a return value is something like Int, String, or Boolean. But Kotlin does not limit you to “primitives”: the return value can be a Pair or a Triple.
For example, if a function computes the minimum and maximum of two numbers, it can return Pair<Int, Int>, where by contract “the first is the minimum, the second is the maximum”:
fun minMax(a: Int, b: Int): Pair<Int, Int> {
return if (a < b) a to b else b to a
}
fun main() {
val result = minMax(10, 3)
println(result.first) // 3
println(result.second) // 10
}
Here a to b creates Pair(a, b) in infix form (that is, “between the values”), and it is literally a call to the to function from the standard library.
From the compiler’s point of view, everything is fair: the function returned one value—an instance of Pair. For us humans, it’s “two related things in one package”.
Result contract: the main agreement
When you return a Pair or Triple, you are essentially telling the calling code: “I’ll return you a box. It has two/three compartments. And you must know what goes where.” This is the result contract: an agreement about the meaning and order of the components.
The most common trap here is this: first/second/third are technical names. They carry no domain meaning. Meaning appears only from context: how you name variables, where you unpack the result, how you document the function.
Look at the contrast:
fun minMax(a: Int, b: Int): Pair<Int, Int> = if (a < b) a to b else b to a
fun main() {
val x = minMax(10, 3)
println(x.first) // 3
println(x.second) // 10
}
This code works, but it’s not very readable: “x.first—what is that, the minimum? the start of a range? an x-coordinate?”.
And now the same thing, but with proper names:
fun minMax(a: Int, b: Int): Pair<Int, Int> = if (a < b) a to b else b to a
fun main() {
val (min, max) = minMax(10, 3)
println("min=$min max=$max") // min=3 max=10
}
Technically it’s the same. But now the result contract has been “pulled out” and made obvious: min and max are labeled right at the point of use. It’s almost like a comment—except it’s a comment that compiles.
To make this easier to keep in mind, it helps to imagine the Pair/Triple contract as a small table in your head (or in a comment above the function):
| The function returns | first means | second means | third means |
|---|---|---|---|
for a range |
|
|
— |
for min/max |
|
|
— |
for statistics |
|
|
|
And yes, the order is part of the contract. If you once decided that “first is min”, then you stick to that. Not “today min/max, tomorrow max/min, because my mood changed”.
Destructuring as documentation at the call site
Many people think destructuring is just “to be shorter”. In reality, in educational and team code it’s often about something else: to be clearer.
When you write:
val (min, max) = minMax(10, 3)
you do two things at the same time. First, you unpack the Pair. Second, you document the contract: first contains the minimum, and second contains the maximum.
A useful habit to build: if you return a Pair/Triple from a function, then at the call site it’s almost always better to destructure the result immediately. Then, later in the code, you work with normal variables rather than “anonymous components”.
2. Practice: parse a string and return 2–3 values
Let’s continue our educational console “mini profile parser”. The idea is simple: the user enters a string like:
"Ada Lovelace, 36" And we want to get the first name, last name, and age separately.
Step 1: split the string by comma and return two parts
First, let’s extract a very small but useful function: “split the string by the first comma”.
Contract: first is the left part, second is the right part (both already trim()’d).
fun splitByComma(text: String): Pair<String, String> {
val commaIndex = text.indexOf(',')
if (commaIndex == -1) return text.trim() to ""
val left = text.substring(0, commaIndex).trim()
val right = text.substring(commaIndex + 1).trim()
return left to right
}
fun main() {
val (a, b) = splitByComma(" Ada Lovelace, 36 ")
println("a='$a' b='$b'") // a='Ada Lovelace' b='36'
}
Note: we are not making life complicated. If there is no comma, we return an empty string as the right part. This is also a contract—just a “contract for bad input”.
Step 2: parse the age and return “value + message”
Sometimes it’s useful to return not only the data, but also an explanation of what happened. For example: we parsed the age—great. We didn’t parse it—return null and the text “age is not a number”.
Contract: first is Int? (a number or null), second is a message for the user/log.
fun parseAge(text: String): Pair<Int?, String> {
val trimmed = text.trim()
if (trimmed.isEmpty()) return null to "Age is not specified"
val age = trimmed.toIntOrNull()
if (age == null) return null to "Age must be a number"
if (age < 0) return null to "Age cannot be negative"
return age to "OK"
}
fun main() {
val (age, message) = parseAge(" 36 ")
println("age=$age message='$message'") // age=36 message='OK'
}
One important point about the contract: we agreed that "OK" means success. We could return a Boolean instead of a string (for example Pair<Boolean, Int>), but a string is more convenient for an educational example: we immediately see “why it didn’t work”.
Step 3: put it all together and return a Triple
Now let’s make a function that returns three results: first name, last name, and age (age can be null if parsing failed).
Contract: first is firstName, second is lastName, third is ageOrNull.
To avoid diving into complex string operations, we’ll search for the last name by a space (the first space separates first and last name). If there is no space, the last name will be an empty string.
fun parseNameAge(line: String): Triple<String, String, Int?> {
val (fullName, ageText) = splitByComma(line)
val spaceIndex = fullName.indexOf(' ')
val firstName = if (spaceIndex == -1) fullName.trim() else fullName.substring(0, spaceIndex).trim()
val lastName = if (spaceIndex == -1) "" else fullName.substring(spaceIndex + 1).trim()
val (age, _) = parseAge(ageText)
return Triple(firstName, lastName, age)
}
fun main() {
val (first, last, age) = parseNameAge("Ada Lovelace, 36")
println("first='$first' last='$last' age=$age") // first='Ada' last='Lovelace' age=36
}
Yes, Triple looks appropriate here: three parts of one entity, a “profile”. But note that Triple does not make our contract understandable by itself. We made it understandable: we unpacked the result into first/last/age, not into a/b/c.
Mini diagram: from input to usage
Sometimes it’s useful to reinforce the overall process. It looks roughly like this:
flowchart TD
A["String input (readln)"] --> B["parseNameAge(line) -> Triple"]
B --> C["val (first, last, age) = ..."]
C --> D["Use first/last/age in the logic"]
And here is where Pair/Triple work really well: the function returns one object, but you immediately “put it on the shelves” at the call site.
3. When Pair/Triple start to hurt readability
At first, Pair feels like a gift: less code, everything compact. But there is a point where compactness starts working against you.
A common symptom: you catch yourself writing something like result.first and you no longer remember what’s inside. Or you end up with variables like p, x, t, res, and you start talking to the code like an archaeologist: “I wonder what the author wanted to say with this inscription on the wall”.
There is an even more obvious red flag: when you return a Pair/Triple but you are forced to write a long comment like “first is…, second is…, third is…”, because otherwise no one will understand. That means your code is already asking for a “named result” (a separate type with fields named by meaning).
We won’t introduce our own data types yet—that’s a topic for the next major blocks of the course—but the idea is worth remembering: Pair/Triple are good as a quick container, not as an official data format.
Rules of good style
When you return 2–3 values via Pair/Triple, try to think not “how do I cram everything into the container”, but “how do I make the contract obvious”.
First, lock in the component order as part of the contract and do not change it depending on your mood. If minMax returns (min, max), then it should always be that way.
Second, almost always destructure the result at the call site and give components meaningful names. val (min, max) = ... is far more readable than val p = ... and then p.first.
Third, don’t make Triple a “bag of everything”. Three values should be parts of a single meaning. If you return Triple(userName, taxRate, planetName), that’s not a “contract”—it’s the beginning of a bad joke.
4. Typical mistakes
Mistake No. 1: a floating component order.
It is very easy to return (max, min) once because “it happened that way”, and elsewhere expect (min, max). From the outside, both variants look the same: Pair<Int, Int>. The compiler won’t save you. Only discipline will: fix the contract once and follow it everywhere.
Mistake No. 2: meaningless names when destructuring.
Formally, val (a, b) = minMax(10, 3) works. But a day later, you yourself will look at a and b as “something first” and “something second”. Destructuring is strong precisely because you can name components meaningfully: val (min, max) = ....
Mistake No. 3: Pair/Triple are used for unrelated data.
Pair is not a “two-seat cart for anything whatsoever”, but a container for a related result. If the values are not parts of one meaning, reading the code becomes a guessing game, and any change becomes a risk of mixing up components.
Mistake No. 4: returning a Triple even though only one part is needed.
Sometimes beginners create a “universal result” for all cases, and then in 80% of places they use only first. This is a signal that the result design does not match real usage. Either return exactly what you need, or revisit the contract.
Mistake No. 5: trying to “hide” meaning inside first/second/third.
Sometimes it’s tempting to think that first is “the main thing”, and second is “secondary”. But for Kotlin, this is simply “first by order” and “second by order”. Don’t attribute magic to the container. The magic should be in your variable names and in a clear function contract.
GO TO FULL VERSION