Passing a function as a parameter helps in dividing complexity logically. For example, a function that iterates through a list of words and converts them to the upper case can be passed to any method that needs this functionality without exposing the list. It lets you delegate the complexity to the function. Here is the code both in Scala and Java.
Scala
First define a method that takes a function as a parameter.
1 2 3 |
def methodA(fn: () => String): String = { fn() } |
The above function fn, takes no parameters and outputs a String. Let’s define a function that takes no parameters and outputs a String, so we can pass it to methodA.
1 |
val functionB = () => "Hi, I am functionB from Scala, I am passed to functionA as a parameter." |
Pass functionB to functionA as below.
1 2 3 |
def message: String = { methodA(functionB) } |
You should see “Hi, I am
Let’s implement the same thing in Java.
Java
1 2 3 4 5 6 7 8 9 10 |
@FunctionalInterface public interface IFunc { String printMessage (); } public String methodA(IFunc funcB) { return funcB.printMessage(); } IFunc functionB = () -> "Hi, I am functionB from Java, I am passed to functionA as a parameter."; |
Pass functionB to functionA as below.
1 2 3 |
public String message() { return methodA(functionB); } |
You should see “Hi, I am