The Pair Type in Kotlin

1 min read 221 words

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}
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts