Sobes.tech
Middle

What are lambda expressions based on?

sobes.tech AI

Answer from AI

Based on the Invoke Dynamic (JSR 292) mechanism. It allows deferring method call resolution until runtime. This makes lambdas more flexible and efficient than using anonymous inner classes for simple functional interfaces.

The Java compiler transforms a lambda expression into a specific construct using the static method lambda$(), which is invoked via invokedynamic.

Example:

// Functional interface
interface MyFunctionalInterface {
    void myMethod();
}

// Using a lambda expression
public class LambdaExample {
    public static void main(String[] args) {
        MyFunctionalInterface myLambda = () -> System.out.println("Hello from lambda!");
        myLambda.myMethod();
    }
}

After compilation, the lambda code will look roughly like this (in bytecode):

  invokedynamic #0:myMethod:()V()LI; // BootstrapMethod:lambda$0
  astore_1
  aload_1
  invokeinterface MyFunctionalInterface.myMethod:()V interface 1

The Bootstrap Method for invokedynamic determines which method to call. In the case of lambdas, it is usually java.lang.invoke.LambdaMetafactory.metafactory(), which generates a class and an instance of the functional interface at runtime, linking it to the lambda implementation (in this case, the static method lambda$0).

This approach reduces overhead in creating numerous anonymous inner classes for simple lambdas, improving performance and memory usage, especially in collections and streams.