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:
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:
With a lambda expression in Kotlin, it would be simplified this way:
Even better, suppose the following classic example of the OnClickListener of a button in Java:
In Kotlin, it is reduced to a single line:
Finally, since the parameter function is unique and the lambda too, I can remove the parentheses with:
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:
Ver la versión en Español de este artículo acá: