Passing Functions as Parameters in Scala & Java

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.

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.

Pass functionB to functionA as below.

You should see “Hi, I am functionB from Scala, I am passed to functionA as a parameter.” in your browser. You can download the complete working example for both Scala and Java from my Git repo below. Here is the video version of this post.

Let’s implement the same thing in Java.

Java

Pass functionB to functionA as below.

You should see “Hi, I am functionB from Java, I am passed to functionA as a parameter.” in your browser. Download the working code from Git repo and run it. Go to http://localhost:8080/scala/passfunc and http://localhost:8080/java/passfunc to see the outputs from both Scala and Java respectively.