Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
Kotlin how to use this in "return (object : interface) { }"
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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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()
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda