Using Pair and Triple
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 the argument provided as the second
value in the Pair
.
The ability to create a pair of objects with such concise syntax is useful. The need to work with a pair of objects is common in programming. For example, if you have a list of airport codes and want to get the temperature at each of these airports, then representing the airport code and temperature as a pair of values is natural. In Java, if you hold the values in an array, it’ll get cumbersome to work with. Besides, we’ll lose type safety since airport code is a String
and temperature is a double
, and the array will end up being of type Object
—smelly. In Java we normally create a specialized class to hold the two values. This approach will provide type safety and remove some noise in code, but it increases the burden on us to create a separate class just for this purpose. Java provides no pleasant way to deal with this. Kotlin Pair solves the issue elegantly.
To see the benefit of Pair
, let’s create an example to collect the temperature values for different airport codes.
Get hands-on with 1400+ tech skills courses.