Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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

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.

  • + Share This
  • 🔖 Save To Your Account