Scala Programming – Difference Between Passing a Value vs Passing a Function as a Parameter

closuresscala

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.

Best Answer

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?