【发布时间】:2017-03-08 08:49:58
【问题描述】:
给定一个包含以下(压缩)类的 Java 库:
public class Vector2f {
public float x;
public float y;
public Vector2f div(Vector2f other) {
x /= other.x;
y /= other.y;
return this;
}
public Vector2f div(Vector2f other, Vector2f dest) {
dest.x = x / other.x;
dest.y = y / other.y;
return dest;
}
/* ... */
}
由于 kotlin 会自动将合适的方法名称转换为重载运算符,所以我可以编写
val v0 = Vector2f(12f, 12f)
val v1 = Vector2f(2f, 2f)
val res = v0 / v1
println(v0)
println(v1)
println(res)
res.x = 44f
println()
println(v0)
println(v1)
println(res)
...完全出乎意料的结果是v0 被中缀除法操作改变了。此外,存储在res 中的引用指向与v0 相同的对象输出:
Vector2f(6.0, 6.0)
Vector2f(2.0, 2.0)
Vector2f(6.0, 6.0)
Vector2f(44.0, 6.0)
Vector2f(2.0, 2.0)
Vector2f(44.0, 6.0)
由于库还提供了将结果写入另一个向量的重载,我想知道是否可以“告诉”kotlin 不要使用提供的Vector2f.div(Vector2f) 方法。
我已经尝试为Vector2f 提供一个扩展方法,但它被真正的成员所掩盖:
operator fun Vector2f.div(other: Vector2f): Vector2f = this.div(other, Vector2f())
^~~ extension is shadowed by a member: public open operator fun div(other: Vector2f!): Vector2f!
【问题讨论】:
-
如果有兴趣,here glm 端口
-
@elect 使用您的端口是最好的解决方案,您为什么不发布答案?
-
怕显得过于坚持/侵略,但既然你建议了,我就试试..
标签: java operator-overloading interop kotlin