Core Java

lambdas and side effects

Overview

Java 8 has added features such as lambdas and type inference. This makes the language less verbose and cleaner, however it comes with more side effects as you don’t have to be as explicit in what you are doing.

The return type of a lambda matters

Java 8 infers the type of a closure. One way it does this is to look at the return type (or whether anything is returned). This can have a surprising side effect. Consider this code.

es.submit(() -> {
    try(Scanner scanner = new Scanner(new FileReader("file.txt"))) {
        String line = scanner.nextLine();
        process(line);
    }
    return null;
});

This code compiles fine. However, the line return null; appears redundant and you might be tempted to remove it.  However if you remove the line, you get an error.

Error:(12, 39) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

This is complaining about the use of FileReader. What has the return null got to do with catching an uncaught exception !?

Type inference

ExecutorService.submit() is an overloaded method.  It has two methods which take one argument.

Both these methods take no arguments, so how does the javac compiler infer the type of the lambda? It looks at the return type.  If you return null; it is a Callable<Void> however if nothing is returned, not even null, it is aRunnable.

Callable and Runnable have another important difference. Callable throws checked exceptions, however Runnable doesn’t allow checked exceptions to be thrown.

The side effect of returning null is that you don’t have to handle checked exceptions, these will be stored in the Future<Void> submit() returns.  If you don’t return anything, you have to handle checked exceptions.

Conclusion

While lambdas and type inference remove significant amounts of boiler plate code, you can find more edge cases, where the hidden details of what the compiler infers can be slightly confusing.

Footnote

You can be explicit about type inference with a cast. Consider this:

Callable<Integer> calls = (Callable<Integer> & Serializable) () -> { return null; }
if (calls instanceof Serializable) // is true

This cast has a number of side effects. Not only does the call() method return an Integer and a marker interface added,  the code generated for the lambda changes i.e. it adds a writeObject() and readObject() method to support serialization of the lambda.

Note: Each call site creates a new class meaning the details of this cast is visible at runtime via reflection.

Reference: lambdas and side effects from our JCG partner Peter Lawrey at the Vanilla Java blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button