Home > Enterprise >  Can I pass a delegated to a variable in Kotlin?
Can I pass a delegated to a variable in Kotlin?

Time:03-16

I use Code A to add a Extensions for Float type, so I can use it with Code B.

But Code B has many repeated code, and it's not easy to use.

So I try to write Code C to improve it, but Android Studio can't compile it.

1: How can I fix Code C?

2: Is there other way to improve Code A and Code B?

Code A

fun Float.toX(originCoordinate: MyPoint) :Float {
    return originCoordinate.x this
}

fun Float.toY(originCoordinate: MyPoint):Float {
    return originCoordinate.y-this
}

class MyPoint (val x:Float, val y: Float)

Code B

val orig = MyPoint(size.width / 2, size.height / 2)

drawPath.moveTo(10.0f.toX(orig), 20.0f.toY(orig))
drawPath.moveTo(5.0f.toX(orig), 80.0f.toY(orig))
drawPath.moveTo(1.0f.toX(orig), 3.0f.toY(orig))
....

Code C

val orig = MyPoint(size.width / 2, size.height / 2)

val toXX = Float.toX(orig)
val toYY = Float.toY(orig)

drawPath.moveTo(10.0f.toXX, 20.0f.toYY)
drawPath.moveTo(5.0f.toXX, 80.0f.toYY)
drawPath.moveTo(1.0f.toXX, 3.0f.toYY)
...

CodePudding user response:

Here's how to fix Code C. Use get() so they are recalculated each time they're accessed. And move Float. before the name to make it an extension property. Where you have it is the syntax for calling a function in the Float companion object, which of course doesn't exist.

// at top level of your class:
var orig = MyPoint(0f, 0f)

private val Float.toXX: Float get() = toX(orig)
private val Float.toYY: Float get() = toY(orig)

// ------

// In a function:
orig = MyPoint(size.width / 2, size.height / 2)

drawPath.moveTo(10.0f.toXX, 20.0f.toYY)
drawPath.moveTo(5.0f.toXX, 80.0f.toYY)
drawPath.moveTo(1.0f.toXX, 3.0f.toYY)

Here's a completely different approach to the problem. You could define extension properties inside your MyPoint class, and then use them if you are inside a run block called on your class:

data class MyPoint(val x: Float, val y: Float) {
    val Float.toXX: Float get() = x   this
    val Float.toYY: Float get() = y - this
}

// In a function:
val orig = MyPoint(size.width / 2, size.height / 2)
orig.run {
    drawPath.moveTo(10.0f.toXX, 20.0f.toYY)
    drawPath.moveTo(5.0f.toXX, 80.0f.toYY)
    drawPath.moveTo(1.0f.toXX, 3.0f.toYY)
}
  • Related