Friday, January 31, 2014

Power Of Closure In Java

Closure is added to java because of the clarity and beauty it gives. You can achieve everything without closure as well but using closure, you can write readable short code which is easier to debug and understand. It gives you enough power which you will salute at the end of this article.

Functional Interface:
An interface with only one abstract method is known as functional interface. Functional interfaces are used at many places like java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable. There are many such interfaces in jdk. These are called functional interfaces. They are used frequently by creating anonymous inner classes.

public class WorkerThread {
  public static void main(String[] args) {
    Thread worker = new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("A new worker is created");
      }
    });
    worker.start();
  }
}

This makes our code unclear and the same can be achieved using lambda expressions in easy way.

public class WorkerThread {
  public static void main(String[] args) {
    Thread worker = new Thread(() -> {
      System.out.println("A new worker is created");
    });
    worker.start();
  }
}

In the declaration the lambda expressions is:
 ( ) -> { 
         System.out.println("A new worker is created"); 
  }



In this way you can declare lambda expressions to simplify your task.

Java have strong typing i.e. it checks the type of every object at compile time, so in closures as well you need to define type. There are a lot of existing Functional Interfaces added to the jdk, they are present in java.util.function package.




public static void testLambda() {
IntToLongFunction p = j -> j * 2;
System.out.println(p.applyAsLong(34));
}

Here, IntToLongFunction is a functional interface which is present in java.util.function package having only one method Long applyAsLong(Integer).

Lambda does not means that you need to replace all your for loops with map, filter and fold methods, do it only where it is making sense.

You can write recursive functions with lambda as you do with normal functions, and doing it will add a great power.



References:
Lambdas are being developed under Project Lambda and JSR-335
Open jdk implementation for Closures for the Java Programming Language
Neal Gafter's blog
Advanced Topics In Programming Languages: Closures For Java
Wikipedia