Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between plus and plusAssign in operator overloading of kotlin?

Tags:

kotlin

I know there are some difference between plus and plusAssign, the latter can't return anything, but I find that the plus can achieve what plusAssign do.

A Point class overloads plus and return a new Point.

 data class Point(var x: Int, var y: Int)
{
    operator fun plus(other: Point): Point
    {
        return Point(x + other.x, y + other.y)
    }
} 

A Point class overloads plusAssign but do not return a new Point.

data class Point(var x: Int, var y: Int)
{
    operator fun plusAssign(other: Point): Unit
    {
       this.x+=other.x
        this.y+=other.y
    }
}

But I find it can also be achieved like this:

data class Point(var x: Int, var y: Int)
{
    operator fun plus(other: Point): Point
    {
       this.x+=other.x
        this.y+=other.y

        return this;
    }
}

So, I can't find something make plusAssign special, is there anything plusAssign can do but plus can't?

like image 989
BlackCat Avatar asked Oct 14 '17 02:10

BlackCat


1 Answers

When you are talking about overloading, you have full control of what the function do, even that you completely swap the implementation of plus and plusAssign (not possible in Kotlin), or even minus. Although you are allowed to do that, it is not suggested.

In general, plus function should be a pure function (function with no side effect) which concatenates two objects and return the concatenated result. It does not change the value of the object. plusAssign should be a mutating function which concatenates the left-hand-side operand with the right-hand-side operand. It mutates the object (left-hand-side operand) instead of passing the result back.

like image 117
BakaWaii Avatar answered Jan 04 '23 04:01

BakaWaii