Gilles Barbier
06/05/2020, 11:39 AMopen class MyInt(open var int: Int = 0) : {
operator fun plus(increment: Int): MyInt = MyInt(int + increment)
}
I can do
MyInt(4) + 3
It works. But now, I would like to extends MyInt
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?diesieben07
06/05/2020, 11:46 AMGilles Barbier
06/05/2020, 2:06 PMdiesieben07
06/05/2020, 2:08 PMplus
operator is modifying the instance now and not creating a new one. Just fyiGilles Barbier
06/05/2020, 2:09 PMGilles Barbier
06/05/2020, 2:29 PMdiesieben07
06/05/2020, 2:30 PMGilles Barbier
06/05/2020, 2:31 PMdiesieben07
06/05/2020, 2:31 PMGilles Barbier
06/05/2020, 2:32 PMMyInt(3) + 3
is not accepted, saying that none of .plus definition match this onediesieben07
06/05/2020, 2:32 PMGilles Barbier
06/05/2020, 2:36 PMoperator fun <T : MyInt> T.plus(increment: Int): T = this.copy(int + increment) as T
on main file it worksdiesieben07
06/05/2020, 2:36 PMGilles Barbier
06/05/2020, 2:36 PMGilles Barbier
06/05/2020, 2:36 PMdiesieben07
06/05/2020, 2:36 PMGilles Barbier
06/05/2020, 2:37 PMGilles Barbier
06/05/2020, 2:56 PMdiesieben07
06/05/2020, 3:00 PMGilles Barbier
06/05/2020, 3:02 PMimport com.zenaton.commons.data.plus
I did not know thatGilles Barbier
06/05/2020, 3:02 PMGilles Barbier
06/05/2020, 3:04 PMdiesieben07
06/05/2020, 3:04 PMdiesieben07
06/05/2020, 3:04 PMGilles Barbier
06/05/2020, 3:05 PMoperator fun invoke() = this
is ok, but
operator fun invoke() = { return this }
is not?diesieben07
06/05/2020, 3:07 PM=
sign means "return the expression on the right hand side". So the 2nd is trying to return { return this }
diesieben07
06/05/2020, 3:07 PMoperator fun invoke() { return this }
, without =
Gilles Barbier
06/05/2020, 3:07 PMoperator fun invoke() { return this }
It does not workdiesieben07
06/05/2020, 3:08 PMoperator fun invoke(): ReturnTypeHere { return this }
Gilles Barbier
06/05/2020, 3:10 PM