
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access Variables from Enclosing Class Using Lambda in Java
The variables defined by the enclosing scope of a lambda expression can be accessible within the lambda expression. A lambda expression can access to both instance, static variables and methods defined by the enclosing class. It has also access to "this" variable (both implicitly and explicitly) that can be an instance of enclosing class. The lambda expression also sets the value of an instance or static variable.
Example
interface SimpleInterface { int func(); } public class SimpleLambdaTest { static int x = 50; public static void main(String[] args) { SimpleInterface test = () -> x; // Accessing of static variable using lambda System.out.println("Accessing static variable 'x': " + test.func()); test = () -> { // Setting the value to variable using lambda return x = 80; }; System.out.println("Setting value for 'x': " + test.func()); } }
Output
Accessing static variable 'x': 50 Setting value for 'x': 80
Advertisements