Java methods mistakenly automatically overload in kotlin

For a Java library containing the following (compressed) class:

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;
    }

    /* ... */
}

Since kotlin automatically converts suitable method names to overloaded operators, I can write

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)

... with a completely unexpected result that v0gets the mutation using the infix division operation. In addition, the link stored in respoints to the same object as v0Exit:

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)

Since the library also provides an overload for writing the result to another vector, I was wondering if I could say “kotlin” so as not to use the provided method Vector2f.div(Vector2f).

I already tried to provide an extension method Vector2f, but which is obscured by the real member:

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!
+4
2

Java, . , /, Kotlin, .

, , , , .

, , - Vector2f, , .

+1

glm-

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_ /=

+3

Source: https://habr.com/ru/post/1671788/


All Articles