10 Higher-order functions:Lambdas as parameters and return values

 

This chapter covers

  • Function types
  • Higher-order functions and their use for structuring code
  • Inline functions
  • Non-local returns and labels
  • Anonymous functions

You were introduced to lambdas in chapter 5, where you explored the general concept, and dove deeper into the standard library functions that use lambdas in chapter 6. Lambdas are a great tool for building abstractions, and, of course, their power isn’t restricted to collections and other classes in the standard library. In this chapter, you’ll learn how to create higher-order functions—your own functions that take lambdas as arguments or return them. You’ll see how higher-order functions can help simplify your code, remove code duplication, and build nice abstractions. You’ll also become acquainted with inline functions—a powerful Kotlin feature that removes the performance overhead associated with using lambdas and enables more flexible control flow within lambdas.

10.1 Declaring functions that return or receive other functions: Higher-order functions

10.1.1 Function types specify the parameter types and return values of a lambda

10.1.2 Calling functions passed as arguments

10.1.3 Java lambdas are automatically converted to Kotlin function types

10.1.4 Parameters with function types can provide defaults or be nullable

10.1.5 Returning functions from functions

10.1.6 Making code more reusable by reducing duplication with lambdas

10.2 Removing the overhead of lambdas with inline functions

10.2.1 Inlining means substituting a function body to each call site

10.2.2 Restrictions on inline functions

10.2.3 Inlining collection operations

10.2.4 Deciding when to declare functions as inline

10.2.5 Using inlined lambdas for resource management with withLock, use, and useLines

10.3 Returning from lambdas: Control flow in higher-order functions