6 Function as the most fundamental block of code

 

After reading this lesson, you will be able to

  • Identify the components of a function
  • Implement functions in Scala
  • Define function parameters with defaults

When coding, functions are the most fundamental block of code. They provide instructions on how to perform a given task; without them, you will not be able to define how your application works. Scala treats functions as its first-class citizens: they are an essential component of your program with different uses and shapes. For example, you can use partial functions, anonymous functions, higher order functions, and more! In this lesson, you’ll review the basics of functions in Scala and analyze their different components. You’ll also see how to define a function. In the capstone for this unit, you’ll use functions to provide instructions on how to operate your vending machine.

6.1 Functions

Suppose you want to determine if a given number is even.

Listing 6.1 The isEven function
def isEven(n: Int): Boolean = {
    n % 2 == 0
}

Summary

Answers to quick checks