```class C object O { operator fun C.plus(othe...
# announcements
a
Copy code
class 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.
🤔 1
https://youtrack.jetbrains.com/issue/KT-24800 Hrm, found it reported as a bug here. Though a surprisingly old one (Jun 2018) for a bug to still be in the compiler, unless it is somehow by design?
t
I guess this should work (because C is final), but the compiler isn't smart enough. An extension function of
C
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
Another side note: This is from the Kotlin documentation
The 
inc()
 and 
dec()
 functions must return a value, which will be assigned to the variable on which the 
++
 or 
--
 operation was used. They shouldn't mutate the object on which the 
inc
 or 
dec
 was invoked.
Obviously 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 receiver
a
Yeah, my code is an attempt at a minimal example to replicate the issue (which I got for a vector math extension function that does indeed create a new incremented instance).
I'm not entirely sure I follow @Tobias Berger. Do I understand you correctly that it could be a special restriction specifically for dec/inc to prevent a mismatch of types not on the receiver, but with the variable being assigned? Either way that's not exactly what the error message is saying, and probably shouldn't be disallowed in this case (but rather if I were actually overriding C as in your example)?
t
like i said - it should work, because C is final. It should also work with certain generics, but it doesn't. So I agree that it's a bug. The restrictions are probably very specific to inc and dec. The error message tells you about this restriction for inc/dec functions, I just tried to explain why this restricion (that shouldn't be an issue here) is in place
👍 1
It's also only a problem with extension functions
v
The same by me at 18.01.2023:
Copy code
data 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.