Lambda Expression Scope


Collapse Content

The scope of a Lambda Expression is similar to, but not the same as, the scope of an anonymous inner class. Local variables that are declared final and fields of the defining class are available.

However, the this keyword actually refers to the defining class. This is because the lambda expression does not actually define an anonymous inner class. It actually defines a method that is called using invokedynamic in the byte-code.

Here's a short example of using lambdas with the Runnable interface:

import static java.lang.System.out;

public class Hello {
    Runnable r1 = () -> out.println(this);
    Runnable r2 = () -> out.println(toString());
    int n = 3;
    Runnable r3 = () -> out.println(n);

    public String toString() { return "Hello, world!"; }

    public static void main(String... args) {
        new Hello().r1.run(); //Hello, world!
        new Hello().r2.run(); //Hello, world!
        new Hello().r3.run(); //3
    }
}

The important thing to note is both the r1 and r2 lambdas call the toString() method of the Hello class. This demonstrates the scope available to the lambda.


You can also refer to final variables or effectively final variables. A variable is effectively final if it is only assigned once.

For example, using Spring's HibernateTemplate:

String sql = "delete * from User";
getHibernateTemplate().execute(session -> 
    session.createSQLQuery(sql).uniqueResult());

In the above, you can refer to the variable sql because it is only assigned once. If you were to assign to it a second time, it would cause a compilation error.

Challenge

What does this refer to in a lambda expression?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

What can the lambda expression refer to without getting a compilation error?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

Use a Java 8 Lambda expression to make a Runnable that prints out "Hello " and a person's name.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us
Sign in or email us at [email protected]