title: Accessing the delegating receiver with by delegation in Kotlin
body: <p>Given an interface:</p>
  
  <pre><code>interface Countable
  {
      val count: Int
  }
  </code></pre>
  
  <p>And an implementation/factory:</p>
  
  <pre><code>fun countable(counter: () -&gt; Int): Countable = object : Countable
  {
      override val count: Int
          get() = counter()
  }
  </code></pre>
  
  <p>I can implement this using the class <code>by</code> delegation feature:</p>
  
  <pre><code>class CountableThing : Countable by countable({ 123 })
  </code></pre>
  
  <p>So that this snippet predictably outputs <code>123</code>:</p>
  
  <pre><code>fun main()
  {
      val countableThing = CountableThing()
      println(countableThing.count)
  }
  </code></pre>
  
  <p>My question is, in the context of the delegate class, is there any way to get an instance of the delegating receiver?</p>
  
  <p>In other words, can my delegate <code>Countable</code> implementation (the anonymous object defined in <code>fun countable</code>) see/access the receiver instance of the <code>CountableThing</code> class?</p>
  
  <p>I tried this:</p>
  
  <pre><code>fun &lt;T&gt; countable(receiver: T, counter: () -&gt; Int): Countable = object : Countable
  {
      // ...
  }
  
  class CountableThing : Countable by countable&lt;CountableThing&gt;(this, { 123 })
  </code></pre>
  
  <p>But that's not valid, because expectedly:</p>
  
  <pre><code>class CountableThing : Countable by countable&lt;CountableThing&gt;(this, { 123 })
                                                               /^^^^
                          'this' is not defined in this context
  </code></pre>