首页 > 解决方案 > 获取对调用函数的类的引用

问题描述

当我有两个类(A 和 B)并且 A 有一个名为 myFunA 的函数然后调用 myFunB(在 B 类内部)时,myFunB 中的代码是否可以获得对用于调用 myFunB 的类 A 的引用?我总是可以将引用作为参数传递,但我想知道 Kotlin 是否有办法让函数确定父调用者的实例。

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?
    }
}

标签: kotlin

解决方案


你可以这样做:

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
    }
}

如果您需要基于反射的方法,请阅读


推荐阅读