Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing outer scope with qualified this in extension functions for inner classes

Tags:

syntax

kotlin

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?

like image 836
neshkeev Avatar asked Nov 07 '22 21:11

neshkeev


1 Answers

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.

like image 82
Alexey Romanov Avatar answered Nov 11 '22 07:11

Alexey Romanov