Delegate to pair

Hello,
I am new to the Kotlin language and I would like to achieve something that maybe doesn’t make sense, but lets see.
So I am using Pair<out Float, out Float> in pair context, so I thought that maybe I can create my own class Point with delegating x and y to first and second properties.
Yes, I am aware that there is a class Point, but for a learning purpose lets say that there is not.
Is there a way to delegate properties to Pair properties?

I’m not sure what do you want to achieve. What do you mean by “delegating x and y to first and second properties” and “delegate properties to Pair properties”? Could you provide some example?

I can use Pair<out Float, out Float> in a class and use .first and .second properties from it, but I would like to use x and y properties, so it is more readable.
So I would like to do something like:

data class Point(val pair: Pair<out Float, out Float>)
{
var x: Float by pair
var y: Float by pair
}

so then I can use Point with x and y like it is Pair<out Float, out Float> with first and second properties.
Maybe it’s not possible since Pair doesn’t have default method for get and set?

You can do it like this:

data class Point(val pair: Pair<out Float, out Float>) {
    val x: Float by pair::first
    val y: Float by pair::second
}

But you need to make properties val. It would be impossible to delegate writable props to read-only props.

Also, what is the point of delegating in this case? Wouldn’t it make more sense to just copy floats instead of delegating them?

edit:
Or maybe I’ll ask in a different way. What is wrong/missing in simple:

data class Point(
    val x: Float,
    val y: Float,
)
1 Like

Well I guess your example is perfectly correct, but since I am learning kotlin I have many that kind of questions.
As far as I understand your example is good enough because Pair doesn’t provide any methods? But if it would be complex class then delegating properties would have more sense?

Of course, as I point at the beginning, I can use Point class that already exists.

Thank you for your help!

Sorry, I don’t really see how delegation is related to existence or inexistence of methods. Also, technically Pair has methods: getFirst() and getSecond() (I ignore the “standard” ones like toString()).

What I meant is if class is complex then delegating it makes your class as powerfull as this class is without much effort. If existed class isn’t complex then there is no much profit in delegating to it.
Or am I missing something?

Ok, I think I understand what you mean. Yes, usually we either delegate the behavior (so functions/methods) or mutable data (properties/fields) in the case we need to sync it across multiple objects.

1 Like