CodeGym /課程 /Kotlin SELF /From a function: returning 2–3 values

From a function: returning 2–3 values

Kotlin SELF
等級 10, 課堂 3
開放

1. Pair/Triple and the result contract

Honestly, 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 parsed a string and want to return both the result and the string “tail”. Or you computed min and max. Or you found coordinates and also computed something from them right away. And here a conflict appears: a function in Kotlin always returns one value.

But as you can probably guess, there is no tragedy in this conflict: one returned value can be a container that holds several parts. Pair and Triple exist precisely to “bundle together” 2–3 values and return them in one package.

Return a container, not “one number”

Previously you were used to the return value being something like Int, String, or Boolean. But Kotlin does not limit you to “primitives”: the return value can also be Pair or 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 is creating Pair(a, b) in infix form (i.e., “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 object of type Pair. For us humans, it’s “two related things in one package”.

Result contract: the main agreement

When you return Pair or Triple, it’s as if you’re telling the calling code: “I will return you a box. It has two/three compartments. And you must know what is in which one.” This is the result contract: an agreement about the meaning and order of components.

The most common trap here is this: first/second/third are technical names. They do not carry domain meaning. Meaning appears only from context: how you named the variables, where you unpacked the result, and how you documented 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—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 is “pulled outward” and becomes obvious: min and max are labeled right at the usage site. It’s almost like a comment, except it’s a comment that compiles.

To make it easier to keep in mind, it’s convenient 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
Pair<Int, Int>
for a range
from
to
—
Pair<Int, Int>
for min/max
min
max
—
Triple<Int, Int, Int>
for statistics
min
max
sum

And yes, order is part of the contract. If you decided once that “first is min”, then that’s how you live going forward. 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 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 once. First, you unpack the Pair. Second, you document the contract: the minimum is in first, and the maximum is in second.

It’s useful to build a habit: if you return Pair/Triple from a function, then at the call site it is almost always better to destructure the result immediately. Then throughout the rest of the code you work with normal variables, not with “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 inputs a string like:

"Ada Lovelace, 36" And we want to obtain the first name, last name, and age separately.

Step 1: split the string by a comma and return two parts

First, let’s extract a very small 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 don’t overcomplicate. If there is no comma, we return an empty string as the right part. That’s 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 data but also an explanation of what happened. For example: age parsed—great. Not parsed—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'
}

An important contract point here: we agreed that "OK" means success. We could have returned 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 fails).

Contract: first is firstName, second is lastName, third is ageOrNull.

To avoid complex string operations, we will find 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 cement the overall process in your head. 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 logic"]

And here Pair/Triple work great: the function returns one object, but you immediately “put it into separate slots” at the call site.

3. When Pair/Triple start to harm readability

At the beginning, 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 is inside. Or you get variables like p, x, t, res, and you start talking to the code like an archaeologist: “I wonder what the author meant by this inscription on the wall”.

There is also a more explicit red flag: when you return Pair/Triple but are forced to write a long comment “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 where fields are named by meaning).

We won’t introduce our own data types yet—this is a topic for the next big 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 etiquette

When you return 2–3 values via Pair/Triple, try to think not “how to cram everything into the container”, but “how to make the contract obvious”.

First, fix the order of components as part of the contract and do not change it depending on mood. If minMax returns (min, max), then it must always be that way.

Second, almost always destructure the result at the call site and give the 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 must be parts of one 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 #1: floating component order.
It’s very easy to once return (max, min) 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 #2: meaningless names during 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 #3: Pair/Triple are used for unrelated data.
Pair is not a “two-seat cart for anything at all”, but a container for a related result. If the values are not parts of one meaning, reading the code turns into guessing, and any change becomes a risk of mixing up components.

Mistake #4: returning a Triple when only one part is needed.
Sometimes beginners make a “universal result” for all occasions, and then in 80% of places use only first. This is a signal that the result design does not match real usage. Either return exactly what you need, or reconsider the contract.

Mistake #5: trying to “hide” meaning inside first/second/third.
Sometimes you want to think that first is “the main thing” and second is “secondary”. But for Kotlin it’s just “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.

1
任務
Kotlin SELF, 等級 10, 課堂 3
上鎖
快速摘要
快速摘要
1
任務
Kotlin SELF, 等級 10, 課堂 3
上鎖
正確的範圍
正確的範圍
1
任務
Kotlin SELF, 等級 10, 課堂 3
上鎖
三項指標
三項指標
1
任務
Kotlin SELF, 等級 10, 課堂 3
上鎖
帶有狀態的搜尋
帶有狀態的搜尋
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION