2

For example, in Java you would add a listener without using lambda as below

view.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });

But this could be replaced in Kotlin some like this

view.setOnCheckedChangeListener({ compoundButton, b -> true})

How is the new instance creation part handled? Does lambda handle the creation of object instance?

rahul.ramanujam
  • 5,608
  • 7
  • 34
  • 56

2 Answers2

3

The listeners you refer to are special kinds of interfaces called SAM interfaces, or "Single Abstract Method" interfaces. Any interface with exactly one abstract method is eligible to be a SAM interface. In Kotlin, you have to explicitly mark such interfaces with fun interface to declare it as such, but in Java we have no such mechanism, so all eligible Java interfaces are treated as SAM in Kotlin.

Any SAM interface can be passed a lambda instead of an object. The runtime will understand that this lambda is meant to be interpreted as an instance of the appropriate interface and will wrap it in the necessary code automatically. This was (I believe; someone may correct me if I'm confused) once done on the Kotlin side, but Java has support for SAM interfaces now as well, and at a brief glance on my end, it looks like Kotlin is compiling to the Java SAM interface mechanism nowadays.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
1

There isn't an instance for a lambda, at least not one you really care about. Kotlin elevates functions (in this case a lambda) to a "first class citizen" so now you can pass an actual function itself as a parameter, not just an object on which you can call the function.

One illustration of this is that, in your Java example, you could refer to the variable this within onCheckedChanged. You can't do that within the lambda because there isn't a meaningful this to refer to.

If you're interested you can read about what the lambdas are actually compiled to under the hood (here for instance) but ultimately you don't need to care. It's just a function.

matt freake
  • 4,877
  • 4
  • 27
  • 56