Kotlin:高阶函数,如何将函数添加到集合并调用它们

Kotlin: Higher order functions, how to add functions to a set and call them

我有一个 class 包含一组函数 ("listeners"),这些函数应该在某个事件上被调用(GPS 在 Android 上更新,但不应该'在这里不重要)。 它看起来像这样(为清楚起见大大简化):

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

现在我正在尝试从另一个 class 添加一个函数到我的集合中,我想在调用 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() 被调用,我知道 "something" 被放入我的集合中,但是 onLocationUpdateReceived 永远不会被调用。

任何人都可以帮助我如何设置它才能正常工作吗?

代码中存在错误

fun addListener(listener: (Location) -> Unit) {
    listeners.add { listener }
}

这里是 add listeners 集合的新 lambda。 lambda 什么都不做,因为您不调用 listener。 正确的代码是

fun addListener(listener: (Location) -> Unit) {
    listeners.add(listener)
}

或者你可以说 add { listener() },但我看不出有什么理由