Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables referenced from a lambda expression must be final

Tags:

java

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.

like image 950
axiorema Avatar asked Nov 08 '16 18:11

axiorema


People also ask

Why local variables referenced from a lambda expression must be final or effectively final?

Forcing the variable to be final avoids giving the impression that incrementing start inside the lambda could actually modify the start method parameter.

Can we use Non final local variables inside a lambda expression?

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.

Why local variables should be final?

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.

Can you pass local variables to lambda expressions?

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.


1 Answers

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);
like image 156
Louis Wasserman Avatar answered Nov 14 '22 23:11

Louis Wasserman