Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin, why can't I access the outer class on an instance of an inner class?

Tags:

kotlin

Why can't I access the outer class's properties on an instance of an inner class?

class A(val id: String) {

    inner class B {}
}

fun test() {
    val a = A("test")
    val b = a.B()
    aid(a)
    bid(b)
}

fun aid(a:A): String = a.id
fun bid(b:A.B): String = b.id //Unresolved reference: id

In this example, b.id fails to compile.

I gather that I have to add a getter on B that returns [email protected]. But why?

like image 258
Jonathan Brown Avatar asked Jan 01 '23 22:01

Jonathan Brown


1 Answers

An inner class just has a reference to the enclosing instance, and therefore does not inherit the outer class's members.

As inner classes have a reference to the enclosing class, this enclosing instance can be accessed within the class only (Java: Outer.this, Kotlin: this@Outer), but you are correct that you cannot access the enclosing instance from outside the inner class.

A class may be marked as inner to be able to access members of outer class.
Kotlin Reference / Nested and Inner Classes

Making your own getter function to return the enclosing instance is the only way to do this.

Though the generated reference to the outer instance is package-private according to Jon Skeet, neither Java nor Kotlin has any method of obtaining this instance. You can use reflection, but as the generated field name is possibly unreliable, your best choice is to modify the inner class.

like image 88
Salem Avatar answered Jan 05 '23 02:01

Salem