Java8:Deep dive to Lambda as a Closure

In Java8 the most important inclusion is the lambda, It is important because  using lambda we can manipulate function/method like data member , also we can pass or returns a function from another function(using java Functional interface). Prior to java8, we can do it by anonymous class but it has a very complex signature.

Now the questions are
what is closure?
How does lambda serve as a closure?
java 8 follows pure closure?
How is Closure useful?

We are going to discuss it one by one.

what is closure?

In a very simple term closure is a function/behavior which uses a variable which is defined out of the scope of this function(method in Java).

This is very common case,

Ex:

public class Greet{
String greet =”Hello”;
public String doGreet(String name){
return greet + name;
}

}

Here, greet is a variable which declared outside of the function scope and we use it in doGreet() function. But the problem arises when a function uses or manipulate an external variable inside a closing function and returns the closing function as a return value.
Hard to understand, let think in this way,  in Java 8 we can pass or returns a function by help of the functional interface, so we can say,  like the value we can also return a function which uses an external variable.

Let's modify the code a bit using Java 8 lambda

package com.example.closure;

import java.util.function.Supplier;

public class Greet {
   
   public Supplier<String>doGreet(String name){
      String salutation = "Hello";
      return () ->salutation + " "+ name;    
             
   }
   
   public static void main(String[] args) {
      Greet greet = new Greet();
      Supplier<String> supplier = greet.doGreet("Shamik");
      String message = supplier.get();
      System.out.println(message);
     
   }

}

How does lambda serve as a closure?

Here, I just modify the code little bit, previously doGreet() directly returns a value by concatenating the name and salutation, Here I return a Functional Interface from doGreet() called Supplier(Java8 built-in functional interface) which takes nothing but produces a String, By doing this I can use that intermediate function, later on.

Here Salutation variable is declared inside doGreet() method but salutation variable used in the intermediate function Supplier<String>, so the state of the salutation variable bound into the intermediate function which is used later when we call supplier.get(). So the state of a variable
Which is defined outside the function is closed by the function or encapsulated by the function, hence the name is closure, Close the state of a foreign variable inside a function.

The closure is a function which wraps a state of a variable which is defined outside of the function and can manipulate the state.


java 8 follows pure closure?

In our example Supplier, the functional interface acts as a closure as it encapsulates the salutation variable which is defined outside of the intermediate function.

But as per the closure definition, we can manipulate the state of the external variable so let's try to modify the salutation variable inside the function.

package com.example.closure;

import java.util.function.Supplier;

public class Greet {
   
   public Supplier<String>doGreet(String name){
      String salutation = "Hello";
      return () ->
      {
          salutation = "welcome";//modifying the state
          return salutation + " "+ name;    
      };
             
   }
   
   public static void main(String[] args) {
      Greet greet = new Greet();
      Supplier<String> supplier = greet.doGreet("Shamik");
      String message = supplier.get();
      System.out.println(message);
     
   }

}


If we try to compile the above code we got a compilation error, the error says
“Local variable salutation defined in an enclosing scope must be final or effectively final”

What it tries to say is -- as salutation defined in doGreet() method, so the scope  of salutation live as long as the doGreet() method executes  by main thread, as the variable creates in stack memory. But here we use  the salutation variable inside the intermediate function Supplier<String>, we can only do this in Java if and only if we guarantee that the value of the salutation is never changed , so by the final modifier we can provide this guarantee  in java8 whether you declare final explicitly or not if you use the variable which is defined outside and use the same in lambda , java8 treats that variable as effective final, whose reference never changed.


But here we try to modify the value inside the intermediate function by assigning the value “welcome”  so the compiler complains the above.


But as per closure definition, we can manipulate the same so Java8 does not act as a pure closure but we can use the value defined outside of the function scope without modifying it which is also very useful, although Java lambda is not a pure closure but it serves most of the closure functionality very well.




How Closure is useful ?

As closure encapsulate a state of variable, so we can apply the state elsewhere in the code which brings a great dynamicity into the code, By closure, we can wrap a behavior and local state together and apply the same as a callback, so we create our own strategy and inject the same into the framework. It is the implementation of Strategy pattern in Functional programming.


Conclusion :Although in Java we have Closure in form of anonymous class previously, java 8 add some syntactic sugar to it. But in spite of that, lambda is very easy to use and we can implement some of the functional style library function, curry function. Which is very tedious to implement using an anonymous class.



Post a Comment