The Pair Type in Kotlin

val pair: Pair<String, Int> = "myKey" to 2

What is a Pair Type?

A utility class when you want to return 2 values that are not related to one another.

Some examples

val (a, b) = Pair(1, "x") println(a) // 1 println(b) // x
Code language: Kotlin (kotlin)

Alterantively, you could use:

val p = Pair("x", "y") println(p) // (x, y)
Code language: Kotlin (kotlin)

You can refer to it as first and second

val p = Pair("x", "y") println(p.first) // x println(p.second) // y
Code language: Kotlin (kotlin)

This is great for returning multiple values from a function.

The to keyword

The shorter version of doing this, is to use a map value with the to keyword:

val p = "x" to "y" println(p.first) // x println(p.second) // y
Code language: Kotlin (kotlin)

Or:

val p = Pair("x" to "y") println(p.first) // x println(p.second) // y
Code language: Kotlin (kotlin)

Using Pairs in function return Types

fun main() { val p = getMyPairs() println(p) // (x, y) } fun getMyPairs() : Pair<String, String> { return Pair("x", "y") }
Code language: Kotlin (kotlin)

And splitting into values:

fun main() { val (first, second) = getMyPairs() println(first) // x println(second) // y } fun getMyPairs() : Pair<String, String> { return Pair("x", "y") }
Code language: Kotlin (kotlin)

Simplifying getMyPairs

fun getMyPairs() : Pair<String, String> { return"x" to "y" }
Code language: Kotlin (kotlin)

Comparing to a mapOf

fun main() { val myMap = mapOf("x" to "y", "z" to "o") println(myMap) // {x=y, z=o} }
Code language: Kotlin (kotlin)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments