Store lambda in a variable in kotlin

后端 未结 2 1118
孤独总比滥情好
孤独总比滥情好 2021-02-19 00:07

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 setL         


        
2条回答
  •  太阳男子
    2021-02-19 00:27

    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. 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.

提交回复
热议问题