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.
You can try this with java8,
IntStream.range(0, 10).forEach(i ->{
someObject.method(() -> otherObj.process(i, i+1))
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With