Kotlin how to use this in "return (object : interface) { }"

Viewed 89
class AImpl : A {
    override fun createB(): B {
        return object : BImpl {
            val t = this

            override fun createC(): C {
                return CBuilderInstance.buildC { // this: CBuilder
                    this.B = t // type: B
                    // How can I use 'this@Something' to replace the t.
                }
            }
        }
    }
}

class CBuilder {

    fun buildC(block: CBuilder.() -> Unit): C {
        ...
    }

}

Sorry that I cannot describe the problem I met.

What can I do to replace "t" in the code? The IDE give me 2 suggestions, "this" and "this@AImpl", which is not working for this.

1 Answers

According to Kotlin Language Specification - This-expressions, a labeled this-expression can have the following forms:

  • this@type
  • this@function
  • this@lambda
  • this@outerFunction

The last 3 forms refer to the implicit receiver of functions/lambdas, which is obviously not what you want. You want to refer to the object created by the object literal object : BImpl { ... }.

The spec says (emphasis mine):

this@type, where type is a name of any classifier currently being declared (that is, this-expression is located in the inner scope of the classifier declaration), refers to the implicit object of the type being declared;

And also in Classifier Declarations, it says,

Important: object literals are similar to object declarations and are considered to be anonymous classifier declarations, despite being expressions.

So although object literals are classifier declarations, they do not have a name that we can write after the @.

To conclude, you cannot use a labeled this expression here, without also changing something else.

You can, for example, declare a local class, which has a name:

class AImpl : A {
    override fun createB(): B {
        class Foo : BImpl {
            override fun createC(): C {
                return CBuilder.buildC {
                    this.B = this@Foo
                }
            }
        }
        return Foo()
    }
}
Related