Wednesday, April 08, 2015

Lambdas are not instance methods

Here is a mistake I made. I had assumed that since a lambda becomes an instance of the functional interface I thought that the lambda would be turned into an instance method.

Runnable run = () -> System.out.println("This class: [" + this.getClass().getName() + "].");

No. I get the following compilation error: Cannot use this in a static content.

In response to the StackOverflow question What is a Java 8 Lambda Expression Compiled to? I found that Sotirios Delimanolis gives a very useful answer, referring to part of the Java 8 Language Specification - 15.27.4. Run-Time Evaluation of Lambda Expressions. He noted that the JLS doesn't say anything about how the code should be compiled, so it is up to the compiler creator to decide whether the lambda's body should be a static or instance method.