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

120
Vistas
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 Respuestas
Responde la pregunta

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 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