Monday, August 21, 2017

Android with Kotlin: Using Lambda Expressions

The lambda expressions that we will see in Kotlin, are not really a complete novelty ..., in Java they can be used and it is something that other languages like C # already have it from approximately the year 2006 (with .Net 3.0 ).

But what are lambda expressions?

Lambda expressions allow you to pass functionality as an argument in a very simple way and without having to use anonymous classes. This makes coding a lot simpler.

Suppose we have the following function:

fun compare(a: String, b: String): Boolean = a.length < b.length

Mediante una expresión lambda se podría hacer los siguiente:

max(strings, { a, b -> a.length < b.length })

"Max" is a function that takes the value of the second argument, where this second argument is itself a function.

The general format of a lambda expression is:

{
   Param1, param2 -> // parameters separated by comma
   Param1 + param2 // code to execute
}

To finish this with a very practical example, let's first consider the implementation of an "OnItemClicListener" in a ListView in Java, traditionally it would look like this:

mListView.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
  int position, long id) {

  Log.d("onItemClick", "Se hizo clic") // my code.

  }
});

With a lambda expression in Kotlin, it would be simplified this way:

mListView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->

    Log.d("onItemClick", "Se hizo clic") // my code.

}

As you can see, the difference in simplicity and reduction of code is extremely appreciable. However, suppose that view and id are parameters which will not be used, the expression could be simplified even more by replacing those arguments that will not be in use by an underscore:

mListView.onItemClickListener = AdapterView.OnItemClickListener { parent, _, position, _ ->

    Log.d("onItemClick", "Se hizo clic") // my code.

}

Even better, suppose the following classic example of the OnClickListener of a button in Java:

button.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v){

doSomething();

}
});

In Kotlin, it is reduced to a single line:

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

If the parameters are not used, directly instead of replacing them with an underscore, you can remove them, leaving:

button.setOnClickListener({ doSomething() })

Finally, since the parameter function is unique and the lambda too, I can remove the parentheses with:

button .setOnClickListener { doSomething() }

Something to point out is that Android Studio itself is guiding us and, if it finds that we can replace the code we write for a lambda expression, we next update it automatically by the hand of the "yellow lamp" that usually appears on the margin Left of our code.

Kotlin Lambda Expressions

You can see a complete and implemented example of this and other issues, in the following application that I left complete in Github:

https://github.com/paveliz/ClimaApp_en_Kotlin

Ver la versión en Español de este artículo acá:

https://paveliz.blogspot.com.ar/2017/08/android-con-kotlin-usando-lambda.html