January 18, 2023

Kotlin Tuples - with Example

In Kotlin, a tuple is a data structure that holds a fixed number of items, where each item can have a different type.

It's similar to a struct or a record in other programming languages. A tuple is defined using the keyword "pair" or "triple" followed by the types of the items inside the parentheses.

For example, a pair of integers can be defined as:

val pairInt: Pair<Int, Int> = Pair(1, 2)

You can access the elements of a tuple using the properties first and second.

val first = pairInt.first
val second = pairInt.second
// or
val(first,second) = pairInt

A triple of integers, string, and boolean can be defined as:

val triple: Triple<Int, String, Boolean> = Triple(1, "Hello", true)


You can access the elements of a triple using the properties component1, component2, component3.

val component1 = triple.component1()
val component2 = triple.component2()
val component3 = triple.component3()

Tuples are useful when you need to return multiple values from a function, or when you want to group related data together without creating a separate class for it.

Last edited on January 18, 2023 by Admin

Latest articles