Software Engineering

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

Alterantively, you could use:

val p = Pair("x", "y")
println(p) // (x, y)

You can refer to it as first and second

val p = Pair("x", "y")
println(p.first) // x
println(p.second) // y

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

Or:

val p = Pair("x" to "y")
println(p.first) // x
println(p.second) // y

Using Pairs in function return Types

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

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")
}

Simplifying getMyPairs

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

Comparing to a mapOf

fun main() {
  val myMap = mapOf("x" to "y", "z" to "o")
  println(myMap) // {x=y, z=o}
}