Chapter 10. Functional Programming

Scala supports both object-oriented programming and functional programming styles. Indeed, as I recorded here on my website, at a presentation in 2018, Martin Odersky, the creator of the Scala language, stated that the essence of Scala is a “fusion of functional and object-oriented programming in a typed setting,” with “functions for the logic” and “objects for the modularity.” Many of the recipes in this book demonstrate that fusion, and this chapter focuses solely on functional programming techniques in Scala—what I’ll refer to as Scala/FP in this chapter.

FP is a big topic, and I wrote over seven hundred pages about it in my book Functional Programming, Simplified. While I can’t cover all of that material in this chapter, I’ll try to cover some of the main concepts. The initial recipes will show how to:

  • Write and understand function literals

  • Pass function literals (also known as anonymous functions) into methods

  • Write methods that accept functions as variables

After that you’ll see some very specific functional programming techniques:

  • Partially applied functions

  • Writing methods that return functions

  • Partial functions

The chapter finishes with two examples that help to demonstrate these techniques.

If you’re not familiar with FP, it can be perplexing at first, so it will definitely help to understand its goals and motivations. Therefore, in the next several pages I’ll try to provide the best introduction to functional programming ...

Get Scala Cookbook, 2nd Edition 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.