Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda