Search code examples
kotlingarbage-collectionoperators

How to properly overload an operator in kotlin


I have a Vec2 class in kotlin.
I overloaded the operator * like this:

operator fun times(v:Float): Vec2 {
    return Vec2(this.x * v, this.y * v)
}

End the behavior is just as I expected, I can use * and *= to scale the vector

var a = Vec2() * 7f; a *= 2f

However, from my understanding what I do here, is I create a new object, by calling Vec2(), every time I use *
Even if I use *= and I do not really need to return anything, as I could just edit the object itself (using this keyword)

Is there any way to overload the *= operator, so that it has the similar behavior to this function?

fun mul(v:Float) {
    this.x *= v; this.y *= v
}

I need my application to run smoothly, and these operators are used quite a lot, I do not want any lags caused by garbage collector's work.


Solution

  • There is no need to create a new object, you should just change your x and y to var's so they become reassignable.

    Doing this will most likely end you up with something like this:

    class Vec2(var x: Float, var y: Float) {
        operator fun times(v: Float) {
            x *= v
            y *= v
        }
    }
    

    Then in your implementation it is as simple as:

    val a = Vec2(1.0f, 1.0f)
        
    a * 2f
    // After this line both x and y are 2.0f
    

    If you really want to overload the *= operator then add the timesAssign operator function instead for more info see the kotlin docs