Hi all, I'm using operator overloading and have is...
# announcements
g
Hi all, I'm using operator overloading and have issues with inheritance, with
Copy code
open class MyInt(open var int: Int = 0) : {
    operator fun plus(increment: Int): MyInt = MyInt(int + increment)
}
I can do
Copy code
MyInt(4) + 3
It works. But now, I would like to extends
MyInt
Copy code
class OtherInt(override var int: Int = 0) : MyInt(int)
I can do
OtherInt(4) + 3
but the output is a
MyInt.
Is there a way for
OtherInt
to benefit from operator overloading without reimplementing it in it?
d
g
thx @diesieben07 I have extended your solution 🙂 https://pl.kotl.in/NeOYppqtn
d
Your
plus
operator is modifying the instance now and not creating a new one. Just fyi
g
your are right ! 🤔
surprisingly, your solution (and my extension) do work in playgroung but not in real life (Intellij Idea)
d
I've tried mine in IntelliJ and it works.
g
hmm, ok strange, thx for letting me know
d
What errors do you get?
g
MyInt(3) + 3
is not accepted, saying that none of .plus definition match this one
d
Can you show the code you have in IntelliJ?
g
if I put the line
operator fun <T : MyInt> T.plus(increment: Int): T = this.copy(int + increment) as T
on main file it works
d
You'll have to import it
g
but if I put this line with classes definitions it does not work anymore
very strange
d
Why? its a method like all others
g
I know I do not understand
d
Like I said, you need to import the function for it to be visible
g
oh!
import com.zenaton.commons.data.plus
I did not know that
thank you very much
For the record, here is the working version https://pl.kotl.in/MkAGYbzvU
d
IntelliJ should suggest that with alt-enter on the plus or even when you autocomplete with ctrl-space
it very much behaves like a normal method call
g
A last question, do you know why
Copy code
operator fun invoke() = this
is ok, but
Copy code
operator fun invoke() = { return this }
is not?
d
the
=
sign means "return the expression on the right hand side". So the 2nd is trying to return
{ return this }
The equivalent of the first with a block body would be
operator fun invoke() { return this }
, without
=
g
sorry, I meant
Copy code
operator fun invoke() { return this }
It does not work
d
When you specify a body for the function like that you need to explicitly state the return type, you cannot let the compiler infer it:
operator fun invoke(): ReturnTypeHere { return this }
g
hmm ok - thank you very much for your help. I've learnt a lot