gpt4 book ai didi

Java 方法错误地在 kotlin 中自动重载

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:47 25 4
gpt4 key购买 nike

给定一个包含以下(精简)类的 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)

由于库还提供了将结果写入另一个 vector 的重载,我想知道我是否可以“告诉”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!

最佳答案

我正在 glm 端口上工作 here

对于您的示例,相关代码是 here

operator fun div(b: Float) = div(Vec2(), this, b, b)
operator fun div(b: Vec2) = div(Vec2(), this, b.x, b.y)

fun div(bX: Float, bY: Float, res: Vec2 = Vec2()) = div(res, this, bX, bY)
fun div(b: Float, res: Vec2 = Vec2()) = div(res, this, b, b)
fun div(b: Vec2, res: Vec2 = Vec2()) = div(res, this, b.x, b.y)

fun div_(bX: Float, bY: Float) = div(this, this, bX, bY)
infix fun div_(b: Float) = div(this, this, b, b)
infix fun div_(b: Vec2) = div(this, this, b.x, b.y)

背后的逻辑很简单,引用你的示例,最短/最简单的代码:

val v0 = Vec2(12f)
val v1 = Vec2(2f)

val res = v0 / v1

总是 创建一个新实例。这在某种程度上遵循了同样写在 Kotlin docs 上的指南。 . inc()dec() 部分仍然存在(同时进行了修改)。

也是尽可能不容易出错的形式(个人经验..)

对于性能关键的场景,当你不想分配一个新的实例时,妥协是放弃运算符重载并使用函数形式:

v0.div(v1, res)

也就是说,将v0除以v1并将结果放入res

如果您希望接收者对象直接改变并容纳结果:

v0 div_ v1

这背后的想法是利用下划线 _ 和等号 = 背后的相似性,并将 div_ 解释为 /=

关于Java 方法错误地在 kotlin 中自动重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42666760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com