Can Kotlin dynamically bind an extra object to an object?

I have a method that must pass in a fixed object paint every time, because this function is called frequently, so I can"t create an object in an inline function.

        //(Canvas.apply(..,..))
            bind(pointPaint)
            drawPoint(pointA)
            drawPoint(pointB)
            drawPoint(pointC)
            drawPoint(pointD)
Mar.28,2021

there is certainly no way to perfectly fit your requirements, because the bind function cannot change the local variables inside another function.

there are also many ways to compromise, such as defining a package-level attribute:

var drawPaint: Paint? = null

then the original function is changed to:

    fun test() {
        Canvas().bindPaintDrawPoints(Paint())(
            arrayOf(PointF(1f, 2f),
                PointF(2f, 2f),
                PointF(3f, 2f),
                PointF(4f, 2f))
        )
    }

    fun Canvas.bindPaintDrawPoints(paint: Paint): (Array<PointF>) -> Unit {
        return {
            drawPoints(paint, it)
        }
    }

    fun Canvas.drawPoints(paint: Paint, points: Array<PointF>) {
        for (p in points) {
            this.drawPoint(p.x, p.y, paint)
        }
    }

Menu