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

mic*_*ohl 1 lambda function set higher-order-functions kotlin

我有一个类,它包含一组应该在某个事件上调用的函数("监听器")(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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试从另一个类中添加一个函数,我想在调用updateListeners()时调用它.

class myOtherClass {

private fun registerLocationListener() {
    myClass.addListener (this::onLocationUpdateReceived)
}

private fun onLocationUpdateReceived(location: Location) {
    // do something with the location data
}
Run Code Online (Sandbox Code Playgroud)

编译器在这里没有给我任何警告,所以我首先假设这是正确的.但onLocationUpdateReceived不会被调用.如果我用.toString()记录我的集合中的项目,我得到

Function1<android.location.Location, kotlin.Unit>
Run Code Online (Sandbox Code Playgroud)

这似乎是我想要的 - 但我对此事的经验有限,所以我可能错了.所以我知道updateListeners()被调用,我知道"东西"被放入我的集合中,但onLocationUpdateReceived永远不会被调用.

任何人都可以帮助我如何设置它以便它有效吗?

Eug*_*nko 6

代码中有错误

fun addListener(listener: (Location) -> Unit) {
    listeners.add { listener }
}
Run Code Online (Sandbox Code Playgroud)

在这里你add是一个新的lambda listeners集合.lambda什么都不做,因为你没有调用listener.正确的代码是

fun addListener(listener: (Location) -> Unit) {
    listeners.add(listener)
}
Run Code Online (Sandbox Code Playgroud)

或者你可以说add { listener() },但我认为没有理由