【问题标题】:Kotlin: Higher order functions, how to add functions to a set and call themKotlin:高阶函数,如何将函数添加到集合并调用它们
【发布时间】:2019-02-20 12:20:46
【问题描述】:

我有一个类包含一组函数(“侦听器”),这些函数应该在某个事件上被调用(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 永远不会被调用。

谁能帮助我如何设置它才能正常工作?

【问题讨论】:

  • listeners.add { listener } 添加 lambda(新函数)而不是您传递的参数。将其更改为 listeners.add(listener) 并查看它是否有效。编辑。迟到的回应:)

标签: function lambda kotlin set higher-order-functions


【解决方案1】:

代码有bug

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

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

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

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

【讨论】:

  • 哦,那些括号 - 不是他们第一次得到我。如果你把这些弄错了,有点难找……非常感谢你指出错误!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多