Understanding Lambdas in Kotlin
Hello World...
When I was transitioning from Java to Kotlin, I noticed that apart from eliminating boilerplate code, lambda expressions are one of the most powerful tools in the Kotlin language as well as high order functions that really simplify the android development process and in this article am going to teach you some of the basic things I learned to get you started using lambdas not only in Kotlin but in other languages too.
What is a lambda?
The simplest definition: A Lambda is an anonymous function that is passed as an expression. It's as simple and straightforward as that. Hence, it is fairly easy to pass them as arguments to methods, return them, or do anything we usually do with normal objects.
Let us get started:
This is a simple function you can relate to without the use of Lambda expressions
The above is a simple function that takes two integer parameters adds them and returns the sum in form of an integer
Now let's look at an equivalent function as a lambda expression.
Let’s break it down
The sum is the Lambda name
The parameter declaration in our case our expression takes two values of type integer
Then the arrow sign then the return type to be returned. Note that if the expression returns nothing the return type should be Unit
Then the body where we define our two variables and the actions to be performed.
This expression can further be simplified to make it shorter and do away with redundancy
Here the Kotlin compile self evaluates and returns the sum of the two values. The only part of a lambda that isn’t optional is the code body.
Lambdas returning no value
Lambdas that return no value use the unit keyword to explicitly tell the compiler that this expression does not return any value
Conclusion
This brings us to the end of this demonstration of using lambdas. I think you can agree that this was fairly easy to learn and write. Keep on practising more as you dig deeper into this topic, there’s so much to learn further ahead and this was just an introductory article to get you started.
Until next time friends.