Thursday, February 08, 2018

Java 8 : Functions

Functional programming in Java, a useful feature was introduced with Java 8 (java.util.function package).

With that, we have the ability to define a function, pass functions to a method as arguments or use already defined methods as functions.

I'll use a simple example to explain a function.


Function  myFunction = n -> n * n
 
I have defined a function here, named as "myFunction". It takes an argument of type Integer and returns an Integer (the square of the number passed in).

We can pass this function to other methods as an argument. The method below takes in a function and an integer, then calls function's apply method with the passed in integer. That applies function to the integer.

public int myMethod(Function func, Integer number) {
    return func.apply(number)
}
 
If we call above method with number 5 like below, we'll get 25 in return.
 
int answer = myMethod(myFunction, 5);

Also we are able to use already defined methods as functions. As an example, if we have following method implemented in myClass,


public class MyClass {
  public Integer calculateSquare(Integer number) {
    return number * number;
  }
}
 
then we can define a function like this that will act similar to myFunction.

Function func = MyClass::calculateSquare;
  
You can find all sorts of functions that you can define in this link. I only used one kind (Function : Represents a function that accepts one argument and produces a result) in the example.

No comments:

Related Posts with Thumbnails