【发布时间】: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