How can I partially delegate methods / fields to Kotlin?
To be specific: here I am trying to inherit the User class from the TraitA interface and implement the marked: Boolean field in the StateA wrapper. This will clear the User implementation because marked is just a status field. Please note: TraitA cannot be a class because I want to use several of these interfaces: User() : TraitA by StateA, TraitB by StateB, ..
/* does not compile (Kotlin M12) */ interface TraitA { var marked: Boolean fun doStaffWithMarked() // must be overridable } class StateA() : TraitA { override var marked = false } class User() : TraitA by StateA(){ override fum doStaffWithMarked() { //...all fancy logic here... } }
An alternative is to implement all in one place:
class User() : TraitA{ override var marked = false
Is there a way / template that could solve this problem with simple and minimal code? Code / bytecode generation is not an option for me.
UPDATE
I did not quite understand this, but doStaffWithMarked() that doStaffWithMarked() unique to each User .
Therefore, I can offer a "semi-bad" solution with runtime statements:
interface TraitA { var marked: Boolean /* must be overridden */ fun doStaffWithMarked() = throw UnsupportedOperationException() } class StateA() : TraitA { override var marked = false } class User() : TraitA by StateA() { override fum doStaffWithMarked() { //...all fancy logic here... } }
The question remains open, since a really good solution would be to verify that doStaffWithMarked() at compile time.
multiple-inheritance delegation kotlin
voddan
source share