1

There are some interfaces or classes blow:

interface ITagProvider {
    fun getTag(): String
}

interface ITagPrinter {
    fun printTag()
}

class TagPrinter(val tagProvider: ITagProvider): ITagPrinter {
    override fun printTag() {
        print(tagProvider.getTag())
    }
}

When using Kotlin delegate to implement the following class, the IDE prompts "'this' is not defined in this context."

class AnyClass: ITagPrinter by TagPrinter(this), ITagProvider {
    override fun getTag() = "AnyClass"
}

I understand that at this moment, an instance of AnyClass has not been created yet. However, how can we achieve this effect? In other words, how can we access the methods of the delegated class(AnyClass) within the proxy class(TagPrinter)?

k314159
  • 5,051
  • 10
  • 32
leimenghao
  • 226
  • 1
  • 10
  • 1
    Did you mean to implement ITagProvider rather than implementing ITagPrinter a second time in your last code block? I don’t think this is possible—chicken and egg problem. By the way, getter functions with no arguments in Kotlin are an anti pattern since there are properties. – Tenfour04 Aug 23 '23 at 11:08
  • 1
    @Tenfour04 This is not exactly true. We still can create a property like: `val printer = TagPrinter(this)`, which means we provide `this` while still running the constructor. Kotlin documentation warns that in this case we may get NPEs, but it is technically possible and allowed. I personally don't like the fact the delegation is more restrictive than the rest of the language and it requires the delegate to be either passed in constructor or instantiated in the static context. I don't see a reason why delegating couldn't be done to one of properties that we define in another place. – broot Aug 23 '23 at 17:34
  • We can even do things like this: `val prop1 = f1(); val prop2 = "hello"; fun f1() = prop2`. It also ends up with a null stored in a non-nullable property. And this is still allowed, because applying restrictions to the object initialization would be pretty annoying. But we do apply them to the delegation :-/ – broot Aug 23 '23 at 17:41
  • @broot You got me~ – leimenghao Aug 24 '23 at 01:54

0 Answers0