Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing Java lambda expressions to capture non-final variables in Java

Tags:

java

lambda

final

Is it possible to have a lambda expression capture a variable that is not effectively final?

I know that my code would work perfectly if it could capture them, currently I have to create a new variable that copies the non-final variable I want to pass into a lambda expression.

final SomeClass otherObj;

for(int i = 0; i < 10; i++) {
    int a = i;
    someObject.method(() -> otherObj.process(a, a+1))
}

I'd like to pass in 'i' instead of having to create a new temporary variable.

like image 324
PaperTsar Avatar asked Nov 22 '25 10:11

PaperTsar


1 Answers

You can try this with java8,

IntStream.range(0, 10).forEach(i ->{
   someObject.method(() -> otherObj.process(i, i+1))
});
like image 147
akash Avatar answered Nov 25 '25 01:11

akash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!