https://kotlinlang.org logo
Title
m

Michał Kalinowski

12/26/2019, 10:23 AM
can someone help me with generics? lets say I already overload
Number
operators and now I want make generics
Point
that will also overload operators based on
Number
, f.e result of
Point<Float> + Point<Float>
should be
Point<Float>
but recently is
Point<in Float>
:<
data class Point<Unit : Number>(val x: Unit, val y: Unit, val z: Unit) {
  operator fun plus(increment: Point<Unit>): Point<in Unit> {
    return Point(x + increment.x, y + increment.y, z + increment.z)
  }

  operator fun minus(increment: Point<Unit>): Point<in Unit> {
    return Point(x - increment.x, y - increment.y, z - increment.z)
  }

  operator fun times(increment: Point<Unit>): Point<in Unit> {
    return Point(x * increment.x, y * increment.y, z * increment.z)
  }

  operator fun div(increment: Point<Unit>): Point<in Unit> {
    return Point(x / increment.x, y / increment.y, z / increment.z)
  }
}
d

Dico

12/26/2019, 12:24 PM
That's the type you're indicating expressly to be returned by your operators. Remove
in
from the type declarations and it should work.
m

Michał Kalinowski

12/26/2019, 3:01 PM
then it will return Point<Number> not an Point<Float>
d

Dico

12/26/2019, 3:51 PM
It will return Point<Unit> as indicated
You probably shouldn't name your type parameter Unit, btw
2
s

StavFX

12/26/2019, 6:58 PM
I guess it would also depend on how you defined the Number operators