I´m trying to create a getValue()
function from a pojo that use summatory of details class values in this sense:
@Transient
public BigDecimal getValue() {
BigDecimal sum = new BigDecimal(0);
details.stream().forEach((detail) -> {
sum = sum.add(detail.getValue());
});
return sum;
}
but I don't know why this the line sum = sum.add(detail.getValue());
provoke this error:
local variables referenced from a lambda expression must be final or effectively final
Can you say me what's I'am doing wrong. Thanks.
Forcing the variable to be final avoids giving the impression that incrementing start inside the lambda could actually modify the start method parameter.
Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final , or a compile-time error occurs where the use is attempted.
final is the only allowed access modifier for local variables. final local variable is not required to be initialized during declaration. final local variable allows compiler to generate an optimized code. final local variable can be used by anonymous inner class or in anonymous methods.
A lambda expression can capture variables like local and anonymous classes. In other words, they have the same access to local variables of the enclosing scope.
You cannot modify variables from inside a lambda. That's just not a thing you're allowed to do.
What you can do here is write this method as
return details.stream()
.map(Detail::getValue)
.reduce(BigDecimal.ZERO, BigDecimal::add);
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