- 2.1 Conditional Expressions
- 2.2 Statement Termination
- 2.3 Block Expressions and Assignments
- 2.4 Input and Output
- 2.5 Loops
- 2.6 Advanced for Loops and for Comprehensions
- 2.7 Functions
- 2.8 Default and Named Arguments L1
- 2.9 Variable Arguments L1
- 2.10 Procedures
- 2.11 Lazy Values L1
- 2.12 Exceptions
- Exercises
2.7 Functions
Scala has functions in addition to methods. A method operates on an object, but a function doesn’t. C++ has functions as well, but in Java, you have to imitate them with static methods.
To define a function, you specify the function’s name, parameters, and body like this:
def abs(x: Double) = if (x >= 0) x else -x
You must specify the types of all parameters. However, as long as the function is not recursive, you need not specify the return type. The Scala compiler determines the return type from the type of the expression to the right of the = symbol.
If the body of the function requires more than one expression, use a block. The last expression of the block becomes the value that the function returns. For example, the following function returns the value of r after the for loop.
def fac(n : Int) = { var r = 1 for (i <- 1 to n) r = r * i r }
There is no need for the return keyword in this example. It is possible to use return as in Java or C++, to exit a function immediately, but that is not commonly done in Scala.
With a recursive function, you must specify the return type. For example,
def fac(n: Int): Int = if (n <= 0) 1 else n * fac(n - 1)
Without the return type, the Scala compiler couldn’t verify that the type of n * fac(n - 1) is an Int.