Lambdas and Anonymous Functions

We'll cover the following

Lambdas are often passed as arguments to functions, but if the same lambda is needed on multiple calls, that may lead to code duplication. We can avoid that in a couple of ways. One is to store a lambda into a variable for reuse. Or we may create anonymous functions instead of lambdas—but consequences follow that design decision. Let’s explore these two options and discuss when to use each.

Using lambdas

In the previous example, we wrote a function to generate the lambdas. If the same lambda is used multiple times, we may save it into a variable and reuse it. There’s one catch, though. When a lambda is passed as argument to a function, Kotlin can infer the type of the parameters. But if we define a variable to store a lambda, Kotlin doesn’t have any context about the types. So, in this case, we need to provide sufficient type information.

Let’s create a variable to store one of the lambdas we passed earlier to the find() method:

Get hands-on with 1200+ tech skills courses.