Given the Pair val coordinates = Pair(2, 3)
, is it possible to name each value so I can do something like coordinates.x
to return 2
? Or is coordinates.first
the only way to access that first value?
This is not supported. You should write a wrapper (data) class for that purposes or you could use Kotlin destructuring declarations:
val (x, y) = coordinates println("$x;$y")
See more here.
Another solution is to define an object
with meaningful extensions for Pair<A, B>
and to bring these extensions into the context using with(...) { ... }
.
object PointPairs { val <X> Pair<X, *>.x get() = first val <Y> Pair<*, Y>.y get() = second }
And the usage:
val point = Pair(2, 3) with(PointPairs) { println(point.x) }
This allows you to have several sets of extensions for the same type and to use each where appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With