我有一个类,其中包含一组应在某个事件(Android上的Gps更新,但在这里不重要)被调用的函数(“侦听器”)。
看起来像这样(为清晰起见大大简化了):
class myClass {
private var listeners = mutableSetOf<(Location) -> Unit>()
fun addListener(listener: (Location) -> Unit) {
listeners.add { listener }
}
private fun updateListeners(location: Location) {
if (!listeners.isEmpty()) {
listeners.forEach {
it.invoke(location)
}
}
}
现在,我试图从另一个类中向我的集合添加一个函数,该类要在调用updateListeners()时被调用。
class myOtherClass {
private fun registerLocationListener() {
myClass.addListener (this::onLocationUpdateReceived)
}
private fun onLocationUpdateReceived(location: Location) {
// do something with the location data
}
编译器在这里没有警告我,因此我首先假设这是正确的。但是不会调用onLocationUpdateReceived。如果我使用.toString()记录集合中的项目,则会得到
Function1<android.location.Location, kotlin.Unit>
这似乎是我想要的-但是我对此事的经验有限,所以我可能是错的。
所以我知道updateListeners()被调用,我知道“东西”被放到我的集合中,但是onLocationUpdateReceived从未被调用。
有人可以帮助我进行设置吗?
最佳答案
代码中有错误
fun addListener(listener: (Location) -> Unit) {
listeners.add { listener }
}
在这里,您为
add
集合listeners
一个新的lambda。 lambda不会执行任何操作,因为您不会调用listener
。正确的代码是
fun addListener(listener: (Location) -> Unit) {
listeners.add(listener)
}
或者您可能会说
add { listener() }
,但我认为没有理由
关于function - Kotlin:高阶函数,如何将函数添加到集合中并调用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54786282/