Store lambda in a variable in kotlin

后端 未结 2 1119
孤独总比滥情好
孤独总比滥情好 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:25

    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. 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()
        }
    }
    

提交回复
热议问题