Home Software Engineering The Pair Sort in Kotlin

The Pair Sort in Kotlin

0
The Pair Sort in Kotlin

[ad_1]

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

What’s a Pair Sort?

A utility class if you need to return 2 values that aren’t associated to 1 one other.

Some examples

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

Alterantively, you might use:

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

You possibly can check with it as first and second

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

That is nice for returning a number of values from a perform.

The to key phrase

The shorter model of doing this, is to make use of a map worth with the to key phrase:

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

Utilizing Pairs in perform return Sorts

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

And splitting into values:

enjoyable essential() {
  val (first, second) = getMyPairs()
  println(first) // x
  println(second) // y
}
enjoyable getMyPairs() : Pair<String, String> {
  return Pair("x", "y")
}

Simplifying getMyPairs

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

Evaluating to a mapOf

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

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here