I often hear that scala has a ability to pass function as a parameter to another function. I would like to know the difference between passing a value as a parameter vs passing function itself as the parameter. How the latter approach brings advantage to the programming. If functions are passed as the parameter how the object references are being created since functions are not tied to any objects.


3 Answers 3


Have you ever used the visitor or strategy patterns, factories or dependency injections? Have you ever passed or asked for an object of type Runnable or Comparator? All these things are ad hoc hacks around missing ability to pass functions.

In the visitor pattern, instead of having accept receive an interface for a visitor, you take a function Element => Unit instead (for the void-returning case). The general concept of visitor is known as catamorphism, of which all sorts of mappings and folds are special cases of.

In the strategy pattern, the strategy interface is just a function. In the wiki example, replace the interface with (Int, Int) => Int.

In the factory method pattern, the whole factory class is a function. In the wiki encapsulation example, ImageReaderFactory is just a (InputStream) => ImageReader function.

A Runnable is just a function () => Unit. A Comparator is just a function (A, A) => Int. I could go on and on and on with this, but suffice to say this: you have been passing functions as arguments all this time, just the hard way.

As to your last question, I do not understand very well what you mean. A function, in Scala, is an object implementing the FunctionN interface, where N represents the arity. Of course, non-object oriented languages are not bound to represent functions as objects. In fact, even object oriented languages are not bound to that -- an int in Java is not an object, so why should a function?


Lazy Evaluation

The advantage is the ability to perform Lazy Evaluation of the expression that is being passed in. Instead of having to calculate the real value of x at the time the expression is passed in. It can create a thunk which defers execution until its absolutely needed.

Why is this useful? One instance is that you can define an infinite list of numbers given an expression.

An example (Haskell)

let fibs = map fst $ iterate(\(a,b) -> (b,a+b)) (1,2)

In this case the value fibs is given an expression which is composed of multiple functions, in this case map fst iterate (and an anonymous expression or lambda).

If fibs was to evaluate immediately it would cause a stack overflow as it would instantly try to calculate an infinite fibonacci sequence. If i were to call

let fibSum = sum fibs

Then that's what would actually happen as sum will immediately try to attempt to evaluate fibs and cause a stack overflow.

However if I were to use fibs with another expression

let fibsEvenSum = sum(takeWhile(< 4000000) (filter even fibs))

This sum will still cause fibs to evaluate, however takewhile will cause the evaluation to end when the list reaches 4 million.


Functions as parameters are useful in many many many ways. Consider Java's Listener/Adapter pattern and general situations where callbacks are needed (event-based APIs). In Java, to have the GUI do something on mouse click or key press you will need to implement whole appropriate Listener interface (or extend Adapter class). Contrast this with just passing a function object to be executed on mouse click (you can see this in C# with its event system). It is much simpler.

There are also many situations where you would want to have a certain algorithm, where a part of it is customizable by using a passed-in function. E.g.

  • A family of functions "notAny", "every", "any", "notEvery" which all take a function parameter and a collection parameter and return true if
    [function returns false for all coll. elem.]
    [function returns true for all coll. elem.]
    [function returns true for any coll. elem.]
    [function return false for any coll. elem]
  • A comparator which compares results of a function upon collection elements, e.g.
    new FuncComparator(Person.getName) would enable you to sort a collection of persons by their name property
  • functions like "map", "filter", "groupBy", which take a function parameter and a collection(s) and produce a new collection. Transformation of old into new collection uses the parameter function somehow. E.g:
    groupBy could take a function and a collection and return a map of lists where lists contain elements of the original collection for which the parameter function returns the same value and this value is the map key.

These are just a few cases where a general algorithm of "go over collection and do X" is greatly improved by functions as first-class objects, because it allows the X to be user-specified through the function parameter. This is not all however... there are more complex uses of functions as parameters (first-class functions), many involving functions which generate functions. You should look at Clojure programming language for examples of these uses.

Edit: I don't know the exact implementation details but generally the implementation uses a class or and interface instance to represent the function in JVM. This class has a priviledged method that gets called when function object is invoked. This plumbing is made by Scala compiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.