How to name components of a Pair
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.
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.
The definition of Pair
in the Kotlin stdlib is as follows:
public data class Pair<out A, out B>(
public val first: A,
public val second: B
) : Serializable
So, if you have an instance p
of type Pair
, you can access the first property only as p.first
. However, you can use a Destructuring Declaration like this:
val (x, y) = p
This is made possible because Pair
is a data class
. Every argument of the primary constructor of a data class gets a componentX()
method, where X
is the index of the parameter. So the above call can be expressed like this:
val x = p.component1()
val y = p.component2()
This makes it absolutely independent from the actual name of the parameter.
If you, however, want to be able to write p.x
, you'll have to go ahead and create your own data class (or use a library):
data class Point(val x : Double, val y : Double)