Skip to Content
Course content

132: Multiple Return Values with Destructuring

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're at a fast-food drive-thru and you order a "Value Meal." The employee doesn't hand you a burger, then wait for you to take it, then hand you fries, then wait again, then finally give you a drink. That would be an incredibly inefficient way to run a business. Instead, they put everything into a single brown paper bag and hand you the bag. You have one object in your hand, but that object contains three distinct things. When you get home, you don't keep the burger inside the bag to eat it; you "destructure" the bag by taking the burger, fries, and drink out and placing them separately on the table.

In Kotlin, we do the exact same thing when a function needs to return more than one piece of information. Since a function can technically only return one thing, we pack our results into a "bag"—usually a data class or a Pair—and then use destructuring declarations to unpack them immediately upon receipt.

Packing the Bag with Data Classes

I usually prefer using a data class over a generic Pair because it gives the "bag" a name, which makes your code much easier to read six months from now. Let's say we're building a game and we need a function that calculates a character's remaining resources after a spell is cast.

data class ResourceResult(val health: Int, val mana: Int)

fun castFireball(currentHealth: Int, currentMana: Int): ResourceResult {
    val manaCost = 20
    val recoilDamage = 5
    return ResourceResult(currentHealth - recoilDamage, currentMana - manaCost)
}

In this example, ResourceResult is our brown paper bag. It bundles the health and mana together into a single return object.

Unpacking on the Fly

Now, here is where the magic happens. You could call this function and then access the properties using dot notation (like result.health), but that's tedious. Instead, we can use destructuring to pull the values out into their own variables in one line.

fun main() {
    val currentHP = 100
    val currentMP = 50

    // This is the destructuring part
    val (newHealth, newMana) = castFireball(currentHP, currentMP)

    println("Health is now $newHealth and Mana is now $newMana")
}

Notice how the variables newHealth and newMana are created and assigned simultaneously? Kotlin looks at the ResourceResult data class, sees that health is the first property and mana is the second, and maps them directly to the variables inside the parentheses. It's clean, it's concise, and it gets rid of the boilerplate.

When Pairs are Enough

Sometimes, creating a whole data class feels like overkill—especially for quick, internal utility functions. In those cases, I use the built-in Pair or Triple classes. These are basically generic bags provided by Kotlin.

fun getMinMax(numbers: List<Int>): Pair<Int, Int> {
    return Pair(numbers.minOrNull() ?: 0, numbers.maxOrNull() ?: 0)
}

// Usage
val (min, max) = getMinMax(listOf(12, 45, 2, 89, 34))

I'll give you a word of caution here: don't overdo it with Pairs. If you find yourself using a Triple or a Pair<Pair<Int, Int>, String>, you've gone too far. At that point, stop and just write a proper data class. Your future self will thank you when you aren't trying to remember if first was the ID or the Timestamp.




📋 Practical Task

Exercise: The Coordinate Splitter

You are working on a mapping application. You have a function that receives a coordinate string in the format "latitude,longitude" (e.g., "34.0522,-118.2437"). Your goal is to write a function that parses this string and returns both values as Double types using a Pair.

Your requirements:

  • Create a function called parseCoordinates that takes a String and returns a Pair<Double, Double>.
  • Inside the function, use split(",") to break the string apart and convert the resulting strings to doubles.
  • In the main function, call parseCoordinates and use destructuring to assign the results to two variables: lat and lon.
  • Print both variables to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.