https://kotlinlang.org logo
#announcements
Title
# announcements
k

karelpeeters

10/13/2019, 6:34 PM
Is it possible to access the outer class instance for another instance of the current inner class? For example, I want to access
other@Outer.x
here but I can't figure out the syntax:
Copy code
class Outer(val x: Int) {
    inner class Inner {
        fun foo(other: Inner): Int = this@Outer.x + other@Outer.x
    }
}
j

jbnizet

10/13/2019, 7:04 PM
Not an answer, but wouldn’t it be simpler and cleaner to do this?
Copy code
class Outer(val x: Int) {
    inner class Inner {
        private val x get() = this@Outer.x
        fun foo(other: Inner): Int = this.x + other.x
    }
}
k

karelpeeters

10/13/2019, 7:30 PM
Ah that's a nice workaround! I'm not sure if it's cleaner but it beats manually adding an explicit field for the outer class and removing
inner
. Thanks!
👍 1
2 Views