andreasmattsson
11/13/2020, 12:46 PMclass C
object O {
operator fun C.plus(other: C): C = this
operator fun C.inc(): C = this
}
Could anyone please explain to me why the second function (inc) is illegal/doesn't compile, but the first is okay (plus)?
Fails with 'operator' modifier is inapplicable on this function: receiver must be a supertype of the return type.
Isn't the receiver (C.
) a supertype of the return type (: C
) in both cases?
This compiles and runs if I move the fun declaration of inc outside the object to root level BTW.andreasmattsson
11/13/2020, 1:04 PMTobias Berger
11/13/2020, 1:07 PMC
could also be called on any object of a class that extends C
. Remember, what happens if you call `a++`: it's basically resolved to a = a.inc()
.
Now imagine you have a class D: C()
and a var a: D
. Your C.inc()
has retunr type C
, so if you run a++
you would try to assign the result of a function returning C
to a variable of type D
Tobias Berger
11/13/2020, 1:12 PMTheObviously your code is just an example, but keep in mind that the inc-function should return a new object and nor (modify and) return the receiverandinc()
functions must return a value, which will be assigned to the variable on which thedec()
or++
operation was used. They shouldn't mutate the object on which the--
orinc
was invoked.dec
andreasmattsson
11/13/2020, 1:14 PMandreasmattsson
11/13/2020, 1:19 PMTobias Berger
11/13/2020, 1:23 PMTobias Berger
11/13/2020, 1:25 PMViktor Sirotin
01/18/2023, 11:47 AMdata class Point(val x: Int, val y: Int)
operator fun Point.unaryMinus() = Point(-x, -y) //OK
operator fun Point.inc() = Point(x + 1, y + 1) //Compiler error
I checked https://youtrack.jetbrains.com/issue/KT-24800https://youtrack.jetbrains.com/issue/KT-24800 I still open.