Chapter 12. built-in higher-order functions: Power Up Your Code

image

Kotlin has an entire host of built-in higher-order functions.

And in this chapter, we’ll introduce you to some of the most useful ones. You’ll meet the flexible filter family , and discover how they can help you trim your collection down to size. You’ll learn how to transform a collection using map , loop through its items with forEach , and how to group the items in your collection using groupBy . You’ll even use fold  to perform complex calculations using just one line of code. By the end of the chapter, you’ll be able to write code more powerful than you ever thought possible.

Kotlin has a bunch of built-in higher-order functions

As we said at the beginning of the previous chapter, Kotlin comes with a bunch of built-in higher-order functions that take a lambda parameter, many of which deal with collections. They enable you to filter a collection based on some criteria, for example, or group the items in a collection by a particular property value.

Each higher-order function has a generalized implementation, and its specific behavior is defined by the lambda that you pass to it. So if you want to filter a collection using the built-in filter function, you can specify the criteria that should be used by passing the function a lambda that defines it.

As many of Kotlin’s higher-order functions are designed to work ...

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.