【问题标题】:Get a reference to the class of the calling function获取对调用函数的类的引用
【发布时间】:2019-12-12 18:08:47
【问题描述】:

当我有两个类(A 和 B)并且 A 有一个名为 myFunA 的函数然后调用 myFunB(在 B 类内部)时,myFunB 中的代码是否有可能获得对 A 类的引用,该引用用于打电话给myFunB?我总是可以将引用作为参数传递,但我想知道 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


【解决方案1】:

你可以这样做:

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

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

【讨论】:

  • 我写道:“我总是可以将引用作为参数传递......” - 我正在寻找一种不将其作为参数传递的解决方案。毕竟,如果 Kotlin 知道调用堆栈,您会认为它可能会以某种方式通知被调用函数,调用它的类的实例是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多