Home > Java > Java Tutorial > body text

What is the scope of use of Java Lambda

PHPz
Release: 2023-05-03 17:13:07
forward
994 people have browsed it

1. Access local variables

You can access the final local variables outside the lambda expression:

final int num = 1;
Converter stringConverter =
        (from) -> String.valueOf(from + num);
 
stringConverter.convert(2);     // 3
Copy after login

But unlike anonymous objects, the variable num does not It needs to be final. Attempting to change the value of num inside a lambda expression is also not allowed.

2. Accessing member variables and static variables

Unlike local variables, we can get access to read and write member variables or static variables inside the lambda expression right. This access behavior is very typical for anonymous objects.

class Lambda4 {
    static int outerStaticNum;
    int outerNum;
 
    void testScopes() {
        Converter stringConverter1 = (from) -> {
            outerNum = 23;
            return String.valueOf(from);
        };
 
        Converter stringConverter2 = (from) -> {
            outerStaticNum = 72;
            return String.valueOf(from);
        };
    }
}
Copy after login

The above is the detailed content of What is the scope of use of Java Lambda. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!