If i do inheritance by delegation, is it possible ...
# announcements
t
If i do inheritance by delegation, is it possible to interact with the parent, from within the delegated class? Say we have:
class MyClass: IDelegate by MyDelegatedClass()
Can i access the MyClass instance from within MyDelegatedClass in any way?
h
I believe to do that you have to do something like
Copy code
class MyClass(val delegate: MyDelegatedClass = MyDelegatedClass()) : IDelegate by delegate
Then you can access it via
delegate
if you'd like
Sorry re-read your question, I had this backwards
t
Hi thank you, This way i can access the delegated class instance from MyClass, then i could pass "this" to the delegated instance, but would prefer not to do this
a
I think @Teknight wants the other way around?
basically you want something like
class MyClass: IDelegate by MyDelegatedClass(this)
right?
h
MyDelegatedClass
has no no knowledge of
MyClass
unless you provide it via something like
class MyClass: IDelegate by MyDelegatedClass(this)
a
but I don't think that
this
is valid there yet
🥚 1
🐔 1
t
Yes, exactly, however i cannot pass this there
a
so I guess you would have to go the val delegate and then set it in init route?
h
Ya
t
No my problem exactly. I made a function to pass this in init, but I would like to not have to do this, since i will create a lot of classes with this delegate
So a lot of classes will have this "attachObject" logic
Oh well, if that is the only solution, then i will keep that. Was hoping there would maybe be some reflection i could use, to get which instance was delegating the MyDelegatedClass instance.
Thank you both 🙂
a
Maybe you can change it so the MyDelegatedClass doesn't need the
this
but only a part of it and you can extract that so you get
Copy code
interface A
class MyA(private val b: PartialB) : A
class FullB(private val partialB: PartialB = PartialB()) : A by MyA(partialB)
class PartialB
And quite possibly maybe there are even better solutions
d
https://github.com/Kotlin/KEEP/issues/155 Upvotes and/or feedback appreciated