What is Triple in Kotlin?
When writing code, we may encounter a situation where we want to return multiple values from a function. There are two common ways to go about this:
- Use a custom object
- Use a list
The custom object approach
You can use a data class to instantiate a new object.
data class Score(
val english: Int,
val maths: Int,
val physics: Int,
)
fun getScore(): Score {
// some code
return Score(65, 96, 81)
}
This approach can work well in simple use-cases, but there are a few problems with this approach. One issue is that you need to create new classes any time multiple return values are needed. Also, consider a scenario where we want to compute the average of the scores. We’ll have to write a function for it, and if we add more properties, we’ll still have to change the code in the function.
The list approach
When we want to return multiple values from a function, we can return a list of those values.
fun getScores(): List<Int> {
// some code
return listOf(50, 75, 87)
}
With this approach, we don’t have to create an extra class and we can easily compute the average of the scores with the available methods in the List<T> class and higher-order functions. A problem here is that the size of the list can change, and all items in a list must be of the same type. In some cases, you’d want the data structure in use to have a constant number of elements, so a list wouldn’t serve the purpose.
Triple
data class Triple<out A, out B, out C> : Serializable
Triple is a datatype that is recommended to store three related values together or return three values from a function. Each value can have its own type.
The constructor of Triple takes in three arguments: first, second, and third.
fun getScores(): Triple<Int, Int, Int> {
// some code
return Triple(70, 86, 94)
}
When trying to access the values contained in the Triple object, we can use the .first, .second, and .third properties to get the first, second, and third values.
Triple also has a Triple.toList() extension function that returns a new list with the contents of the Triple object.
With Triple, you don’t need to create extra classes, you can access each property in the Triple object and also get a list, and always be sure that Triple contains three values.