[英]How to properly overload an operator in kotlin
I have a Vec2 class in kotlin.我在 kotlin 中有一个 Vec2 class。
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 *
但是,根据我的理解,我在这里Vec2()
的是,每次我使用*
Even if I use *=
and I do not really need to return anything, as I could just edit the object itself (using this
keyword)即使我使用*=
并且我真的不需要返回任何内容,因为我可以编辑 object 本身(使用this
关键字)
Is there any way to overload the *=
operator, so that it has the similar behavior to this function?有没有办法重载*=
运算符,使其具有与此 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.我需要我的应用程序能够顺利运行,并且这些操作符被大量使用,我不希望垃圾收集器的工作造成任何滞后。
There is no need to create a new object, you should just change your x and y to var
's so they become reassignable.无需创建新的 object,您只需将 x 和 y 更改为var
,以便它们可以重新分配。
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如果您真的想重载*=
运算符,请添加timesAssign
运算符 function 以获取更多信息,请参阅 kotlin 文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.