Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name components of a Pair

Tags:

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?

like image 326
Dick Lucas Avatar asked Jan 07 '18 00:01

Dick Lucas


2 Answers

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.

like image 164
dniHze Avatar answered Oct 27 '22 21:10

dniHze


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.

like image 37
hotkey Avatar answered Oct 27 '22 22:10

hotkey