Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

The Pair Sort in Kotlin

[ad_1]

val pair: Pair = "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 {
  return Pair("x", "y")
}

And splitting into values:

fun main() {
  val (first, second) = getMyPairs()
  println(first) // x
  println(second) // y
}
fun getMyPairs() : Pair {
  return Pair("x", "y")
}

Simplifying getMyPairs#

fun getMyPairs() : Pair {
  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}
}

[ad_2]



This post first appeared on Best Tech 247 Microsoft Silver Certified Partner, please read the originial post: here

Share the post

The Pair Sort in Kotlin

×

Subscribe to Best Tech 247 Microsoft Silver Certified Partner

Get updates delivered right to your inbox!

Thank you for your subscription

×