![]() |
VOOZH | about |
In programming, we often use functions to perform specific tasks. One of the main benefits of functions is that we can call them as many times as we need, and they return a result after performing some computation. For example, an add() function will always return the sum of two numbers we pass to it. However, a function in Kotlin (and most languages) can only return a single value at a time.
What happens if we want to return multiple values especially values of different data types from a function? One way is to define a custom class with all the variables we want to return and then return an object of that class. But if many functions in our program need to return multiple values, this approach becomes cumbersome, verbose, and increases the complexity of the code. To solve this problem, Kotlin provides Pair and Triple simple classes that allow us to return two or three values respectively without the need to create a custom class.
In Kotlin, the Triple class is a generic data type designed to hold exactly three values in a single object. These three values can be of different types. It is simply a container and does not imply any special relationship between its values. The only condition for two Triple objects to be considered equal is that all their three elements must be equal.
Class Definition:
data class Triple<out A, out B, out C> : SerializableThere are three parameters:
In Kotlin, the constructor is a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. To create a new instance of the Triple we use:
Triple(first: A, second: B, third: C)Example:
Output:
1
Geeks
2.0
We can either receive the values of the triple in a single variable or we can use the first, second, and third properties to extract the values.
Example:
Output:
Hello Geeks
This is Kotlin tutorial
[10, 20, 30]
toString():
The toString() function returns the string representation of a Triple.
fun toString(): StringExample:
Output:
String representation is (5, 5, 5)
Another string representation is (Geeks, [Praveen, Gaurav, Abhi], 12345)
As we have learned in previous articles, extension functions provide the ability to add more functionality to the existing classes, without inheriting them.
toList():
This function returns the List equivalent of the given Triple.
fun <T> Triple<T, T, T>.toList(): List<T>Note: This works only if all three values are of the same type (T).
Example:
Output:
[1, 2, 3]
[Hello, 2.0, [10, 20, 30]]