New overloading operator methods


#1

I am writing a glm java porting here and looking for an overloading operator support I stumbled over Kotlin and I fell in love with it…

There is only one problem I am facing right now… I’d like to have the case where I perform this addition

var a = Vec2(1f, 2f)
var b = Vec2(3f, 4f)
var c = a + b

operator fun plus(other: Vec2): Vec2 = Vec2(x + other.x, y + other.y)

where c is a new instance… no problem so far. But I’d also like to have support for the case when c is already initialized and I just want to overwrite its x and y variables…

var a = Vec2(1f, 2f)
var b = Vec2(3f, 4f)
var c = Vec2()
c.set(a + b)

operator fun plus(other: Vec2): FloatArray = floatarrayof(x + other.x, y + other.y)

The big problem here is that I cannot have simultaneously these two operator overloading functions…

Do you have a tip how I could find a solution (even tricky) about it?


#2

Why don’t you just use Vec2 as an argument of set()?
What is the advantage of having plus returning FloatArray and not Vec2?


#3

In order to minimize the garbage collector activity…

There are some situations where I don’t want to have any garbage (or at least as less as possible), that is, if I have a pool of Vec2, I can re-use for example c to save the result of a + b


#4

FloatArray as a result also requires an allocation.
Anyway you couldn’t have an overload of a function that differs only in return type, so you have to choose another name for plus that returns an array.


#5

You could provide an operator += in Vec2:

class Vec2 {
    operator fun plusAssign(other: Vec2): Unit {
         this.x += other.x
         this.y += other.y
    }
}

and then you can add vectors in-place with no allocations as following:

var a = Vec2(1f, 2f)
var b = Vec2(3f, 4f)
val c = Vec2(a)  // copy constructor 
// or c = a.copy() if Vec2 is a data class
c += b

But now you have to declare c as val, since having both plus and plusAssign available on a mutable variable leads to an ambiguity of expression c += b.


#6

I’d like to have the possibility to override basic operations as following

a = b + c

operator fun addition(a: Vec2, b: Vec2): Vec2 {
    x = a.x + b.x
    y = a.y + b.y
    return this;
}

in order to save result in a without creating any intermediate garbage result…

According to Perry Nguyen, this is possible in Scala:

[quote=“Perry Nguyen, post:6, topic:2007, full:true”]it would end up being something like a := b / c, where := would be defined as def :=(ops: Vec2Op) = a.append(ops.calculate) and b / c would evaluate as a Vec2Op
[/quote]


#7

[quote=“Perry Nguyen”]it would end up being something like a := b / c, where := would be defined as def :=(ops: Vec2Op) = a.append(ops.calculate) and b / c would evaluate as a Vec2Op
[/quote]

Note that Vec2Op also could be considered as intermediate garbage result.