Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How Does Lambdas Work In Java

In this post , i will show how lambdas in Java work , with a simple example .Consider the following Code snipped using java lambda .

package java8Test;

import java.io.File;
import java.io.FileReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LambdaTest2 {


public static void main(String[] args) {

ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(()-> {
File f = new File("abcd.txt");
FileReader reader = new FileReader(f);
//use reader to read stuff
return null ;
});
}
}
The above code compiles fine , now if you remove return statement(which seems redundant here) from above code , it fails to compile with following error :

Unhandled exception type FileNotFoundException
Reason for this behavior is , ExecutorService's submit method has two overloaded versions . One takes Callable , and the other one takes Runnable , Both methods have no arguments . So , which one the java compiler chooses ?It looks for return type as well . When you write return statement , it creates Callable and when you return nothing , it creates Runnable . Since Runnable does not throw Checked Exceptions , that is why you get compile time errors in the code .You can explicitly cast it to Callable by using cast operator like this :

service.submit((Callable)()-> {
You can add marker interfaces also in the cast like this :

Callable calls = (Callable & Serializable) () -> { return null; };
Lambda Removes a lot of boilerplate code , but it might behave differently if you don't know how it works .You can go to original link here


This post first appeared on JavaRoots, please read the originial post: here

Share the post

How Does Lambdas Work In Java

×

Subscribe to Javaroots

Get updates delivered right to your inbox!

Thank you for your subscription

×