Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 47 / 68

Functions That Return Multiple Values (Pair)

In this lesson you will learn how to return several values from one function in Kotlin using Pair, so you are not limited to a single return value. This is for anyone searching for "Kotlin Pair multiple return values".

Pair<A, B> returns two values from a function as one unit. It is a handy fit when you want to hand back two related results, such as a minimum and a maximum.

The sample code declares the return type as fun minMax(nums: List<Int>): Pair<Int, Int> and returns both with Pair(nums.min(), nums.max()). The caller receives them together through the destructuring val (min, max) = minMax(...).

A common stumbling block for beginners is the destructuring syntax. Pulling the contents of a Pair out as separate variables needs the special val (a, b) = pair form.

In real-world development you pick to suit the number of values: Triple or a data class when you want to group three or more.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)