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
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.
© 2024 OneMinuteCode. All rights reserved.