(Sniffles, Kotlin, Android) val listener = CompoundButton.OnCheckedChangeListener { buttonView, isChecked -> ...} This is a question from.

Asked 2 years ago, Updated 2 years ago, 21 views

val listener = CompoundButton.OnCheckedChangeListener { buttonView, isChecked -> ...}

There's a total mental breakdown in this single line of Cotlin coding.

If you take the above "listener" with ctr+q in the Android studio, type is "ComoundButton.OnCheckedChangeListener" appears. And "Comound Button.The OnCheckedChangeListener " appears as interface.

I'm self-taught, but it's hard. I guess I had to learn Java first.

android

2022-09-20 20:55

1 Answers

The interface cannot, of course, be instantiated. However, as you asked in question 3, the object that inherited and implemented the interface is correct. What the hell does this mean?

Originally, prior to the first appearance of the lambda function in Java 8, the Listener interface was used to convey what to run. In this case, what you deliver is an anonymous class called an anonymous class that implements the interface.

view.setOnClickListener(new View.OnClickListener() {
    @override
    public void onClick(View view) {
        doSomething();
    }
})

Same behavior Kotlin code:

view.setOnClickListener { view ->
    doSomething()
}

As you said, this lambda expression is correct for overriding a single abstract method. This is called the Single Abstract Method (SAM) Conversations, which allows only interfaces with one abstract method to write code in lambda form. https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions

You can also write code for the same behavior without using SAM Conversions in Kotlin.

view.setOnClickListener(object: View.OnClickListener {
    override fun onClick(v: View?) {
        doSomething()
    }
})

It's late, but I hope it helps.


2022-09-20 20:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.