0

Is there a way to access name variable having a reference to object B without modifying B class?

class A {
    val name = "Name"
    
    inner class B {
        
    }
    
}

val b: A.B = ...

Maybe there is a way of getting reference to A object having variable b?

  • 1
    Unfortunately you cannot do this without modifying B https://stackoverflow.com/questions/52088622/in-kotlin-why-cant-i-access-the-outer-class-on-an-instance-of-an-inner-class – Steyrix Mar 17 '23 at 12:11
  • @VitaliTsirkunov You have a contradiction between the title and the text of your post: "outer object" vs "reference to A class". "Outer object" = instance of A, "reference to A class" = the class A. First case: not possible as already mentioned by Steyrix. Second case: just us A. – lukas.j Mar 17 '23 at 12:25

1 Answers1

1

You have to expose the A reference from within B:

class A {
    inner class B {
        val a get() = this@A
    }
}

Now you can access a with val a: A = someB.a

Jorn
  • 20,612
  • 18
  • 79
  • 126