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

1
2
3
val (a, b) = Pair(1, "x")
println(a) // 1
println(b) // x

Alterantively, you could use:

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

You can refer to it as first and second

1
2
3
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:

1
2
3
val p = "x" to "y"
println(p.first) // x
println(p.second) // y

Or:

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

Using Pairs in function return Types

1
2
3
4
5
6
7
fun main() {
  val p = getMyPairs()
  println(p) // (x, y)
}
fun getMyPairs() : Pair<String, String> {
  return Pair("x", "y")
}

And splitting into values:

1
2
3
4
5
6
7
8
fun main() {
  val (first, second) = getMyPairs()
  println(first) // x
  println(second) // y
}
fun getMyPairs() : Pair<String, String> {
  return Pair("x", "y")
}

Simplifying getMyPairs

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

Comparing to a mapOf

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