2

When I have two classes (A and B) and A has a function called myFunA which then calls myFunB (inside of class B), is it possible for code in myFunB to obtain a reference to the class A that is used to call myFunB? I can always pass the reference as a parameter but I am wondering if Kotlin has a way of allowing a function to determine the instance of the parent caller.

class A {
    fun myFunA() {
        val b = B()

        b.myFunB() {

        }
    }
}

class B {
    fun myFunB() {
       // Is it possible to obtain a reference to the instance of class A that is calling
       // this function?
    }
}
Johann
  • 27,536
  • 39
  • 165
  • 279

1 Answers1

0

You can do it like this:

interface BCaller {
    fun B.myFunB() = myFunB(this@BCaller)
}

class A : BCaller {
    fun myFunA() {
        val b = B()
        b.myFunB()
    }
}

class B {
    fun myFunB(bCaller: BCaller) {
        // you can use `bCaller` here
    }
}

If you need a reflection-based approach, read this.

IlyaMuravjov
  • 2,352
  • 1
  • 9
  • 27
  • 1
    I wrote: "I can always pass the reference as a parameter..." - I was looking for a solution that doesn't pass it as a parameter. After all, if Kotlin knows the call stack, you would think that maybe it could somehow inform the called function what the instance is of the class calling it is. – Johann Dec 12 '19 at 19:01