Whenever we want to return two values from a function, we make classes for that but creating too many classes can make your code inefficient.
So, Instead of creating classes for two or more values, you can use Pair for returning or using two values and Triple for returning or using three values
Pair in kotlin
Declaring pair using Pair Constructor -
val myPair = Pair(first = "Shivam", second = 22)
Accessing Pair values using 'first' and 'second' member variable -
println(myPair.first)
println(myPair.second)
Receiving Pair through function , We can get the Pair values with the named variables also like this-
val (name, age) = getPersonInfo()
println("Name: $name, Age: $age")
fun getPersonInfo(): Pair<String, Int> {
return Pair("John", 20)
}
Converting a Pair into a List type
val myPair1 = Pair("Hi", "Developers")
val list: List<String> = myPair1.toList()
println("List: $list")
Triple in kotlin
Declaring triple using Triple Constructor
val myTriple = Triple(first = "Dhruv", second = 25, third = 10000.0F)
Accessing Triple value using 'first', 'second', and 'third' member variable -
println(myTriple.first)
println(myTriple.second)
println(myTriple.third)
Receiving Triple through function , We can get the Triple values with named variables also like this-
val (empName, empAge, empSalary) = getEmployeeInfo()
println("Employee Name: $empName")
println("Employee Age: $empAge")
println("Employee Salary: $empSalary")
fun getEmployeeInfo(): Triple<String, Int, Float> {
return Triple("John", 20, 25000.5F)
}
Multiple Pair inside the Triple
val myTriple2 = Triple(
first = Pair(first = "Pair1 Value1", second = "Pair1 Value2"),
second = Pair(first = "Pair2 Value1", second = "Pair2 Value2"),
third = Pair(first = "Pair3 Value1", second = "Pair3 Value2")
) val myTriple2 = Triple(
first = Pair(first = "Pair1 Value1", second = "Pair1 Value2"),
second = Pair(first = "Pair2 Value1", second = "Pair2 Value2"),
third = Pair(first = "Pair3 Value1", second = "Pair3 Value2")
)
Accessing values of multiple pair from a triple
println(myTriple2.first.first)
println(myTriple2.first.second)
println(myTriple2.second.first)
println(myTriple2.second.second)
println(myTriple2.third.first)
println(myTriple2.third.second)
Converting a Triple into a List type
val myTriple1 = Triple("Hi", "Hello", "Bye")
val list1: List<String> = myTriple1.toList()
println("List: $list1")
We can use any different data type with Pair and Triple like String, Int, Float, List, ArrayList, etc.