Extension functions inside class


(Updating this to simplify code.)

In this example, within the extension function B.ext(), is there a way to access the x from A? Or, in other words, is there a way to get at the “this” for A.  If I say “this” in B.ext() it refers to the instance of B.


class B {
  val x = 2

class A  {
  val x = 1
  fun B.ext() {
  println(“x = $x”)  // gets x from B

  fun test(b: B) {

fun main(args: Array<String>) {
  val a = A()
  val b = B()
  // b.ext()

Declare member extensions outside the class

Use "this@A.x":

  fun B.ext() {   println("x = ${this@A.x}")  // gets x from B   }



Followup: is there a way to write an extension function for a class that is itself an extension function?  In other words, to add B.ext() to A after A is defined elsewhere.  I tried syntax like fun A.B.ext() {...} but it didn’t parse.

The use case: I’m copying the example HTML builders [1] for use in Javascript, building the DOM. That example defines String.plus as an extension function inside the Element class. But in my variation I’m using the existing org.w3c.dom.Element class (and it’s subclasses HTMLDivElement, etc).  If I put String.plus outside that class, it’s available everywhere which isn’t ideal.


[1] http://kotlinlang.org/docs/reference/type-safe-groovy-builders.html


No, multiple receivers are not supported at the moment. We have this in our backlog, but it's hard to say when we'll get to it.

We are also aware of the issue of limiting the scope of extensions (like String.plus) for DSL purposes. We have some ideas about it, but no final decision.