java-ee - JAVA8 lambdas expression changes the value of external variables
天蓬老师2017-06-12 09:24:10
0
3
950
As shown in the picture, I defined an etotalPrice externally, and then tried to change this value in two for loops, but an error was reported to me. How to solve it? (NumberUtil.add and mutiplyu are the basic *methods of retaining 2 decimal places)
In Java's classic books "Effective Java" and "Java Concurrency in Practice", the masters mentioned that variable references in anonymous functions, also called variable reference leaks, can lead to thread safety problems. Therefore, before Java8, if To reference a function local variable inside an anonymous class, it must be declared final, that is, an immutable object.
Java8 adds a syntax sugar here: within lambda expressions and anonymous classes, if a local variable is referenced, it will be treated directly as final.
I suggest you refactor this code: use lambda to return a value and assign it to an external variable.
It means that totalPrice in the lambda expression should be of final type. The final type cannot be changed after it is initialized, so it will be an error to assign a value to totalPrice again. So you should redefine a variable to save the new value instead of copying the value to totalPrice again. If changing the variable is not possible, don't use lambda expressions.
In Java's classic books "Effective Java" and "Java Concurrency in Practice", the masters mentioned that variable references in anonymous functions, also called variable reference leaks, can lead to thread safety problems. Therefore, before Java8, if To reference a function local variable inside an anonymous class, it must be declared final, that is, an immutable object.
Java8 adds a syntax sugar here: within lambda expressions and anonymous classes, if a local variable is referenced, it will be treated directly as final.
I suggest you refactor this code: use lambda to return a value and assign it to an external variable.
It means that totalPrice in the lambda expression should be of final type. The final type cannot be changed after it is initialized, so it will be an error to assign a value to totalPrice again. So you should redefine a variable to save the new value instead of copying the value to totalPrice again. If changing the variable is not possible, don't use lambda expressions.
Final, of course, immutable. If you must change, don’t use lambda. If you use lambda, don’t modify the value