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

319
Visualizações
How to get a class instance inside a lambda expression in Kotlin?

In java when I want to get the outer class instance from an Inner class I'm writing OutClass.this. In Kotlin, inside a lambda expression is there a way to get an instance of the class where the lambda expression is written if the lambda is running with a receiver? Lets say we have the following code:

class Dog
{
    fun funcA () : Unit
    {
        println("Dog funcA")
    }
}  
class OuterClass
{ 
   var d : Dog = Dog()
   fun funcA () : Unit
   {
        println("OuterClass funcA")
   }
   
  fun funcWithLambda() : Unit
  {
      d.apply(){
         //place where I want to call OutClass method *funcA*
         // writing *this* will refer to *Dog* instance
         }
  }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You're looking for this@OuterClass.funcA().

over 4 years ago · Santiago Trujillo Relatório

0

I'm allergic to labels, so much prefer to assign to explicitly named variables:

val outer: OuterClass = this
d.apply() {
    val inner: Dog = this
    outer.funcA()
    inner.funcA()
}

Even better is to avoid different this contexts entirely (obviously your example is contrived, so so is this one):

fun funcWithoutLambda(): Unit {
    funcA()
    d.funcA()
}
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