Pair and Triple in Kotlin
--
It is a very common use case where we want to return two values from a method, can be either of same data type or can be of different data types.
This post was originally posted at https://agrawalsuneet.github.io/blogs/pair-and-triple-in-kotlin/ and reposted on Medium on 17th Aug 2018.
What usually we do there is either create some local variables if the method is of the same class and set those variables from the method and consume them in the place where needed or we create a class with just two variables and return that class object from the method.
This approach works fine but is it worth defining a new class every time when we return two value from a method. what if we have several methods which return two values but each method returns the values of different data types. Are we going to create a separate class for each method?
The answer is NO.
Kotlin provides us with a predefined class Pair
which can be used for the same. Pair
is used to store or return two values of same or different data types. There can or cannot be any relation between both the values. They can be of the same or different data types.
And how do I use it?
Initialise it as a simple Pair
class object by passing two values to the constructor.
Pair ("Hello", "How are you")
Pair ("First", 1)
Pair (10, null)
Pair (1.5, listOf(null))var variable1 = "I am a String"
var variable2 = 10
Pair (variable1, variable2)
And how do I retrieve the values?