Home > Back-end >  How can I assign a variable with the value of another variable in Kotlin?
How can I assign a variable with the value of another variable in Kotlin?

Time:06-11

In Code A, the parameters x1 and x2 use the same vaule, it works well.

I think I can improve Code A, so I write Code B, but it failed.

How can I assign x2 with the value of x1 ?

Code A

val stepWidth = step * index
it.drawChildnAxis(
   x1 = stepWidth.toX, y1 = 0f.toY,
   x2 = stepWidth.toX, y2 = yAxisLength.toY
)

fun Canvas.drawChildnAxis(x1:Float, y1:Float,x2:Float,y2:Float){
    drawLine(
        Offset(x = x1, y = y1),
        Offset(x = x2, y = y2),
        paintTableAxisChild
    )
}

Code B

it.drawChildnAxis(
   x1 = step * index.toX, y1 = 0f.toY,
   x2 = x1, y2 = yAxisLength.toY
)

//The same

CodePudding user response:

The x1 = ..., x2 = ... etc in your code are not actually assignment statements! They are named arguments.

There is no variable x1, x2 etc that becomes suddenly in scope at the function call, allowing you to assign values to it. This is just a bit of a syntax that lets you say the names of your parameters to make your code more readable, and sometimes resolve overload resolution ambiguities.

The syntax just so happened to be designed to look similar to assignments, making the left hand side look like a new variable just got declared. Would you still have this confusion if the syntax used : instead of =?

it.drawChildnAxis(
   x1: stepWidth.toX, y1: 0f.toY,
   x2: stepWidth.toX, y2: yAxisLength.toY
)

So x2 = x1 doesn't make sense - there is no such variable as x1 at that position. x1 is only the name of a parameter, which is only in scope when you are inside drawChildnAxis.

If you want to avoid repetition, just create a new variable yourself!

val x = stepWidth.toX
it.drawChildnAxis(
   x1 = x, y1 = 0f.toY,
   x2 = x, y2 = yAxisLength.toY
)

If you don't want x to be accessible afterwards, use a scope function:

stepWidth.toX.let { x ->
    it.drawChildnAxis(
        x1 = x, y1 = 0f.toY,
        x2 = x, y2 = yAxisLength.toY
    )
}

All of this is of course assuming that toX doesn't have side effects - calling its getter twice on the same thing gives the same value.

  • Related