Kotlin Pair and Triple | Android Introduction #24

ibrahimcanerdogan
2 min readJan 22, 2024

--

In this reading, you will learn more about Present Pair and Triple classes and learn to use the to function.

UDEMY COURSE

Pair and Triple

In some cases, you need to represent a pair of values. For that, a class you can use is the Pair class. This is a data class with two constructor properties, you do not need to define it, as it is distributed with Kotlin.

In the below example, a pair with values of type Double and Char is created. You can read those values using first and second properties. You can also destructure it into variables.

fun main() {
val pair = Pair(1.0, 'A')
println(pair.first) // 1.0
println(pair.second) // A
val (number, letter) = pair
// the type of number is Double
// the type of letter is Char
println(number) // 1.0
println(letter) // A
}

There is also another way to create a pair: by placing the to function between two values. The result is a pair of those two values.

fun main() {
val pair = 1.0 to 'A'
println(pair.first) // 1.0
println(pair.second) // A
val (number, letter) = pair
// the type of number is Double
// the type of letter is Char
println(number) // 1.0
println(letter) // A
}

Another such class is called Triple, and it is used to keep three values on properties first, second and third.

fun main() {
val pair = Triple(1F, "ABC", true)
println(pair.first) // 1.0
println(pair.second) // ABC
println(pair.third) // true
val (number, letters, boolean) = pair
// the type of number is Double
// the type of letters is Char
// the type of boolean is Boolean
println(number) // 1.0
println(letters) // ABC
println(boolean) // true
}

In this reading, you learned more about Kotlin Pair and Triple classes. 👏🏻💯

İbrahim Can Erdoğan

LINKEDIN

YOUTUBE

UDEMY

GITHUB

--

--

ibrahimcanerdogan
ibrahimcanerdogan

Written by ibrahimcanerdogan

Hi, My name is Ibrahim, I am developing ebebek android app within Ebebek. I publish various articles in the field of programming and self-improvement.

No responses yet