axiorema axiorema - 29 days ago 16
Java Question

Local variables referenced from a lambda expression must be final

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.

Answer

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);