Although I spoke a little about itin another article, I’d like to explain in depth how lambdas work in Kotlin, and how they transform the interfaces with a single method in lambdas when we are working with Java libraries.

In particular I’m going to show you some examples on how to simplify the use of the Android Framework, and we’ll see the setOnClickListener of the Android views in detail.

SetOnClickListener transformation

One of the features I like most about Kotlin is that it simplifies the work with the Android framework thanks to some conventions .

For example, the setOnClickListener function, which in Java is defined as:

public void setOnClickListener(OnClickListener l) {
...
}

When we use it in Kotlin, it corresponds to the following:

funsetOnClickListener(l: (View) -> Unit)

This saves us the need to have to create an anonymous implementation of the interface, greatly simplifying the initialization of UI components.

Using setOnclickListener . The original way

Following the above, we’ve already saved enough code. This is what we would have if we had to create an anonymous class of OnClickListener :

If you don’t use the parameter of a lambda, you can remove the left side of the function

This is true if you only have one parameter. The view ( v ) isn’t being used, so we can remove it:

view.setOnClickListener { toast("Hello") }

In addition, in functions that only receive a parameter, instead of defining the left side, we could use the reserved word it , saving some characters.

For example, if we used the view to pass it to another method:

view.setOnClickListener { v -> doSomething(v) }

We have the option to simply use it :

view.setOnClickListener { doSomething(it) }

Your friends, the Lambdas

You see that the code difference is quite important. And not only for the characters you save (about 70%), but it greatly improves readability .

Instead of having to skip all the code that does nothing to find the useful part, we just write what really matters.

If you want to learn a lot more about all this and get enough fluency to create your own Android Apps, I recommend you toget the free guide to learn how to build your first project, or justget the book and learn how to create a complete App from scratch.