Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!