2 Getting started with functional programming in Kotlin

 

This chapter covers

  • Defining higher-order functions that pass functions as parameters to other functions
  • Writing loops in a functional way using recursion
  • Abstracting HOFs to become polymorphic
  • Calling HOFs with anonymous functions
  • Following types to implement polymorphic functions

In chapter 1, we committed ourselves to use only pure functions. From this commitment, a question naturally arises: how do we write even the simplest of programs? Most of us are used to thinking of programs as sequences of instructions executed in order, where each instruction has some kind of effect. In this chapter, we begin learning how to write programs in the Kotlin language by combining pure functions.

In this chapter, we introduce some of the basic techniques for how to write functional programs. We discuss how to write loops using tail-recursive functions, and we introduce higher-order functions (HOFs). HOFs are functions that take other functions as arguments and may themselves return functions as their output. We also look at some examples of polymorphic HOFs where we use types to guide us toward an implementation.

2.1 Higher-order functions: Passing functions to functions

2.1.1 A short detour: Writing loops functionally

2.1.2 Writing our first higher-order function

2.2 Polymorphic functions: Abstracting over types

2.2.1 An example of a polymorphic function

2.2.2 Calling HOFs with anonymous functions

2.3 Following types to implementations

Summary