Chapter 11. lambdas and higher-order functions: Treating Code Like Data

image

Want to write code that’s even more powerful and flexible?

If so, then you need lambdas. A lambda—or lambda expression—is a block of code that you can pass around just like an object. Here, you’ll discover how to define a lambda , assign it to a variable , and then execute its code . You’ll learn about function types, and how these can help you write higher-order functions that use lambdas for their parameter or return values. And along the way, you’ll find out how a little syntactic sugar can make your coding life sweeter .: Treating Code Like Data

Introducing lambdas

Throughout this book, you’ve seen how to use Kotlin’s built-in functions, and create your own. But even though we’ve covered a lot of ground, we’re still just scratching the surface. Kotlin has a pile of functions that are even more powerful than the ones you’ve already encountered, but in order to use them, there’s one more thing you need to learn: how to create and use lambda expressions.

A lambda expression, or lambda, is a type of object that holds a block of code. You can assign a lambda to a variable, just as you can any other sort of object, or pass a lambda to a function which can then execute the code it holds. This means that you can use lambdas to pass specific behavior to a more generalized function.

Using lambdas in this way ...

Get Head First Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.