Although scala is functional programming language, still its not very far from object oriented programming. In this section we will see how functions are internally implemented as objects in Scala.

Functions as objects

  1. Function values are treated as objects in Scala.
  2. The function type A => B is just an abbreviation for the class Function1[A, B] , which is defined as follows.
    package scala 
    trait Function1[A, B] { 
      def apply(x: A): B 
  3. So functions are objects with apply methods.
  4. There are also traits Function2 , Function3 , … for functions which take more parameters (currently up to 22).


Anonymous functions as objects

An anonymous function such as (x: Int) => x * x is expanded to:

  class AnonFun extends Function1[Int, Int] {
    def apply(x: Int) = x * x
  new AnonFun

or, shorter, using anonymous class syntax:

new Function1[Int, Int] {
  def apply(x: Int) = x * x

Function calls

A function call, such as f(a, b) , where f is a value of some class type, is expanded to f.apply(a, b).

So the OO-translation of

val f = (x: Int) => x * x

would be

val f = new Function1[Int, Int] {
  def apply(x: Int) = x * x

Note: “apply” method is not a function value. If it was, it would again be converted to a function object and result in an infinite loop.

Functions and Methods

A method such as “def f(x: Int): Boolean = …“,  is not itself a function value.

But if f is used in a place where a Function type is expected, it is converted automatically to the function value (x: Int) => f(x) or, expanded:

new Function1[Int, Boolean] { 
  def apply(x: Int) = f(x)