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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With