ArraysIntroduction to ScalaSome basic data typesWriting functions

Writing functions

Scala function definitions look very much like mathematical function definitions. For instance, in mathematics we would define a function \(f\) as follows

\[ f : \mathbb{Z} \times \mathbb{Z}\rightarrow \mathbb{Z},\; f(a, b) = a + b \]
In Scala, this function would be written like this
scala> def f(a:Int, b:Int) : Int = a + b
f: (a: Int,b: Int)Int
scala> f(3, 9)
res1: Int = 12
Note that we have indicated the type of each parameter of the function as well as the type of the result.

The body of the function is a block of statements. A block can either be a single expression as in function f above, or it consists of several statements surrounded by curly braces:

def g(a: Int, b : Int) : Int = {
  val m = a*a - b*b
  val s = a - b
  m/s
}
As mentioned above, indentation has no meaning to the Scala compiler at all. Nevertheless, you should indent your programs to be readable!

One big difference between Scala and Python, C, or Java is that no return statement is needed in functions. The function automatically returns the value of the last expression in the function body. You can still use return statements when you want to return from the function earlier.

You have to write the name of each parameter type for a Scala function. The result type is actually optional—you can try to omit it, and see if the Scala compiler can figure it out. I recommend always writing the result type until you have more experience in Scala programming. Including the result type also makes your program easier to read.

Like in Python, every Scala function returns a value. A function that does not need to return anything will return the special value (), the only object of the special type Unit, similar to the special value None in Python.

So a function that returns nothing useful could be written like this:

def greet(name : String) : Unit = {
  println("Hello " + name)
}
Since this case is common, Scala provides a special shorthand notation for it:
def greet(name : String) {
  println("Hello " + name)
}
So we omit both the result type and the equals sign.

The parameters of a function are val variables, and so it is not allowed to change their value inside the function. This is different from Python, Java, and C. So the following is illegal:

def test(a: Int) {
  a = a + 7  // illegal!
  println(a)
}
ArraysIntroduction to ScalaSome basic data typesWriting functions