将lambda存储在Kotlin中的变量中 [英] Store lambda in a variable in kotlin
问题描述
我开始使用Kotlin在Android中进行开发,但是lambdas出现问题.我有一个函数可以在我的视图中设置一个侦听器,如下所示:
I'm starting developing in Android with kotlin and I have a problem with lambdas. I have a function to set a listener in my view, this looks like this:
fun setListener(listener: () -> Unit) {
}
问题是作为lambda传递的代码将不会在setListener函数中执行,它将在代码的另一部分(特别是在选择微调器的项目时)执行,因此我必须保存"或将此lambda存储"到变量/属性中,以便我可以在需要时执行它.关于如何做的任何想法?
The problem is that the code passed as lambda won't be executed in setListener function, it will be executed in another part of my code (specifically when an item of a spinner is selected) so I have to "save" or "store" this lambda into a variable/property so that I'm able to execute it when needed. Any idea about how to do it?
我已经做到了:
private var listener: (() -> Unit)? = null
fun setListener(listener: () -> Unit) {
this.listener = listener
}
有更好的方法吗?谢谢
推荐答案
以下是您的操作方法:
class Foo {
private var listener: () -> Unit = {}
fun setListener(listener: () -> Unit) {
this.listener = listener
}
}
但是,在Kotlin中不建议手动编写二传手.相反,您可以将自己的媒体资源公开:
However, manually writing setters is discouraged in Kotlin. Instead, you can just make your property public:
class Foo {
var listener: () -> Unit = {}
}
作为参考,这里是关于属性的文档,其中包含许多示例.
For reference, here are the docs about properties with lots of examples.
这篇关于将lambda存储在Kotlin中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!