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 })
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.
}
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() })
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.
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
No comments:
Post a Comment