Kotlin is all about lambdas! In this video, take a closer look at why their use helps you to write concise code. Annyce covers their syntax, how they can be passed as function parameters, and more.
- [Instructor] Kotlin is all about lambdas, so let's take a closer look at why their use helps us to write concise code. We're going to start by reviewing their syntax, then how they can be passed as function parameters, and finally, how to use them with Java functional interfaces. This is a lambda. Let's break it down piece by piece. On the left side of the equal sign is the type of the lambda. In this case, it takes in an integer and returns a Boolean as its value.
It's important to understand this syntax, although in practice, the type of the lambda is not often seen in code. On the other side of the equal sign is the expression. It always has opening and closing curly braces. This is what you'll see most often when working with lambda expressions. On the left side of the arrow is a listing of the parameters to the lambda. In this case, there's only one, and it's of type integer. On the right side of the arrow is the lambda's body.
This is the piece of work that this lambda will perform. In our example, it's going to mod our input parameter with two, then compare that value to zero in order to determine if our number is even or odd. Lambdas can also be passed as function parameters. Here's a simple example, based loosely on what's available in the standard library for collections. We have a filter method that takes in a lambda as a parameter. This lambda knows how to take a user object, perform a check on it, and then return true or false.
And the check that we choose to return is whether the user's name is empty or not. If it's not empty, then it passes the filter check. And once you start seeing how simple it is to use lambdas as parameters, I'm sure you'll think of even more use cases for them. Finally, we said that you can use lambdas with Java functional interfaces. These are interfaces that declare a single abstract method, which is why they're also known as SAM interfaces. Here's an example where we have the OnClick listener available in the Android SDK.
This only has one method, OnClick. Before Java 8, this is how we would have to write it, by creating a new anonymous class, and then explicitly overriding the OnClick method. However, if we use Kotlin's lambdas, we can remove that extra boilerplate, and get to the code we care about directly. Since we make use of a lot of SAM interfaces in the Android SDK, the use of lambdas can really streamline our code.
- What Kotlin has to offer
- Working with lambdas
- Common Android extension functions
- Kotlin Android Extensions overview
- Making use of the Anko library
- Working with coroutines
- Nullability and collections