Lambdas and Anonymous Functions
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.
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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access