2 Getting started with functional programming in Scala

 

This chapter covers

  • Introducing the Scala language
  • Explaining objects and namespaces
  • Working with higher-order functions (passing functions to functions)
  • Working with polymorphic functions (abstracting over types)
  • Following types to implementations

Now that we have committed to using only pure functions, a question naturally emerges: How do we write even the simplest of programs? Most of us are used to thinking of programs as sequences of instructions that are executed in order, where each instruction has some kind of effect. In this chapter, we’ll begin learning how to write programs in the Scala language by just combining pure functions.

This chapter is mainly intended for those readers who are new to Scala, functional programming, or both. Immersion is an effective method for learning a foreign language, so we’ll just dive in. The only way Scala code will look familiar rather than foreign is by looking at a lot of Scala code. We’ve already seen some in the first chapter, and in this chapter, we’ll start by looking at a small but complete program. We’ll then break it down piece by piece to examine what it does in some detail to better understand the basics of the Scala language and its syntax. Our goal in this book is to teach functional programming, but we’ll use Scala as our vehicle, and need to know enough of the Scala language and its syntax to get going.

2.1 Introducing Scala the language

2.1.1 Running our program

2.2 Objects and namespaces

2.3 Higher-order functions: Passing functions to functions

2.3.1 A short detour: Writing loops functionally

2.3.2 Writing our first higher-order function

2.4 Polymorphic functions: Abstracting over types

2.4.1 An example of a polymorphic function

2.4.2 Calling higher-order functions with anonymous functions

2.5 Following types to implementations

2.6 Conclusion

Summary

2.7 Exercise answers