简体   繁体   English

将 lambda 存储在 kotlin 中的变量中

[英]Store lambda in a variable in kotlin

I'm starting developing in Android with kotlin and I have a problem with lambdas.我开始使用 kotlin 在 Android 中进行开发,但我在使用 lambdas 时遇到了问题。 I have a function to set a listener in my view, this looks like this:我有一个函数可以在我的视图中设置一个监听器,它看起来像这样:

fun setListener(listener: () -> Unit) {
}

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.问题是作为 lambda 传递的代码不会在 setListener 函数中执行,它将在我的代码的另一部分执行(特别是在选择微调器的项目时)所以我必须“保存”或“存储”将此 lambda 转换为变量/属性,以便我能够在需要时执行它。 Any idea about how to do it?关于如何做到这一点的任何想法?

Edit: I've achieved it by doing:编辑:我已经通过以下方式实现了:

private var listener: (() -> Unit)? = null

fun setListener(listener: () -> Unit) {
    this.listener = listener
}

Is there a better way to do it?有没有更好的方法来做到这一点? Thanks谢谢

Here's how you can do it:您可以这样做:

class Foo {
    private var listener: () -> Unit = {}
    fun setListener(listener: () -> Unit) {
        this.listener = listener
    }
}

However, manually writing setters is discouraged in Kotlin.但是,在 Kotlin 中不鼓励手动编写 setter。 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.作为参考,这里是关于带有大量示例的属性文档

You can store a function in a property easily.您可以轻松地将函数存储在属性中。 The simplest way:最简单的方法:

var listener: (() -> Unit)? = null

Usage:用法:

foo.listener = { println("called") }

If you want your property to be set-only, you can create one public property with unusable getter and one private property for internal use.如果您希望您的属性仅设置,您可以创建一个具有不可用 getter 的公共属性和一个供内部使用的私有属性。 Full example:完整示例:

class Example {

    // for internal use
    private var _listener: (() -> Unit)? = null

    // public set-only
    var listener: (() -> Unit)?
        @Deprecated(message = "set-only", level = DeprecationLevel.ERROR)
        get() = throw AssertionError() // unusable getter
        set(value) { _listener = value } // write-through setter

    fun somethingHappend() {
        _listener?.invoke()
    }
}

Here is a simple example.这是一个简单的例子。

fun main(){
    val result=::sum //function assign to variable (first method)
    val result1: (first: Int, second: Int) -> Int=::sum //function assign to variable (second method)
    print(result(5,6))

}
fun  sum(first:Int,second:Int):Int{
    return first+second;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM