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.
Scala Programming – Difference Between Passing a Value vs Passing a Function as a Parameter
closuresscala
Related Topic
- C# vs Functional Programming – Object Oriented Design or Functional Programming?
- Functional Programming Scala – Why Scala Requires Functions to Have Explicit Return Type
- Functional Style – Are Closures with Side-Effects Considered Functional Style?
- Functional Programming vs. OOP – Comparing with Classes
- Java Development – How New Java Development Influences Interoperability with Scala and Clojure
- Is duplicate syntax for defining named functions a bad language design decision
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
orComparator
? 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 functionElement => 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
. AComparator
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, whereN
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 -- anint
in Java is not an object, so why should a function?