Lambdas and the one liner setOnClickListener() in Kotlin

  • Posted by:

    Adhish L

    • June 06, 2019

    Lambdas and the one liner setOnClickListener() in Kotlin

Before we start, let's understand what are Lambda functions.

Lambda functions are anonymous functions in programming and it came from Lambda Calculus. It allows us to write nameless functions with the ability to write closures! Isn't this amazing?

As the title says, we will take the example of setOnClickListener() to understand the Lambda functions and eventually we will end up with The one liner setOnClickListener()

Let's start!

In Kotlin, lambdas as first-class citizens, which means they can be stored in a variables and data structures, passed as arguments to and returned from other higher-order functions (a function that takes functions as parameters, or returns a function). This means, you have the flexibility of using it any possible way!

For a while, let's come back to the old Java way of implementing onClickListeners. We use to write something like this:

myView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Your action code

Now, let's rewrite the above code completely in Kotlin:

view.setOnClickListener(object : OnClickListener {
override fun onClick(v: View) {
//Your action code
} })

Luckily, Kotlin allows some optimisations over Java libraries, and any function that receives an interface with a single function can be substituted by a lambda. It will work as if we had defined setOnclickListener() like this:

fun setOnClickListener(listener: (View) - > Unit)

A lambda expression is defined by specifying the function input arguments at the left of the arrow (surrounded by parentheses), and the return type at the right. In this case, we get a View and return Unit (nothing). So with this in mind, we can simplify the previous code a little:

view - > //Your action code

Now we can even get rid of the left part if the input values are not being used i.e the variable view:

//Your action code

As the rule says, if the last argument of a function is also a function, we can move it out of the parentheses:

//Your action code

Again, another rule of Kotlin - If the function is the only parameter, we can get rid of the parentheses. So finally, the code comes down to one line it becomes:

view.setOnClickListener {
//Your action code


Amazing! Almost five times smaller than our old Java code and much easier to understand. Not only this, it saves a lot of time to write the code.

Read Next

Native iOS Dev's first try at getting React

Posted by:

Pooja Anian

Read More Blogs


Next Blog Last Blog All Blogs