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

125
Visualizações
Accessing outer scope with qualified this in extension functions for inner classes

How can I access outer scope from an inner class when I create an extension function for it?

Example

class A {
    inner class B {
        fun own() = this@A
    }
}

This code compiles and executes as it is supposed to.

When I add the following extension function

fun A.B.ext() = this@A

The compilation fails with

Error:(7, 22) Kotlin: Unresolved reference: @A

I read the documentation for qualified this and it briefly mentions extension functions, but without any example.

Is it possible to access outer scope from extension functions?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

An extension function can only do things a non-extension fun ext(x: A.B) can do, so I would expect not, just like you can't access it in Java. This is because it compiles to such a function, the syntax just makes it look like a member.

While class B has a field containing a reference to the outer A instance, this field can't be accessed directly from code by name. Allowing access to it would violate encapsulation.

The linked page talks about "access[ing] this from an outer scope". "Scope" here is used in the sense of https://en.wikipedia.org/wiki/Scope_(computer_science), so in the example you have scopes where the comments say "implicit label"

class A { // outer scope 1
    inner class B { // outer scope 2
        fun Int.foo() { // function scope
        }
    }
}

while

fun A.B.ext() = ...

doesn't have any outer scopes (except for file scope, which doesn't have this). Unless it's really

class C {
    fun A.B.ext() = // can use this@C
}

but you can't write this@A or for that matter this@B because the function isn't defined in the scope of class A or class B.

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