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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With