Search⌘ K
AI Features

Using Pair and Triple

Explore how to use Kotlin's Pair and Triple to group two or three values safely and efficiently. Understand their practical uses, benefits for type safety, and when to choose these over custom classes or other collections.

We'll cover the following...

What are tuples?

Tuples are sequences of objects of small, finite size. Unlike some languages that provide a way to create tuples of different sizes, Kotlin provides two specific types: Pair for a tuple of size two and Triple for a size of three. Use these two when you want to quickly create two or three objects as a collection.

The Pair tuple

Here’s an example of creating a Pair of Strings:

println(Pair("Tom", "Jerry")) //(Tom, Jerry)
println(mapOf("Tom" to "Cat", "Jerry" to "Mouse")) //{Tom=Cat, Jerry=Mouse}

First we create an instance of Pair using the constructor. Then we use the to() extension function, that’s available on any object in Kotlin, to create pairs of entries for a Map. The to() method creates an instance of Pair, with the target value as the first value in the Pair and ...