java-ee - JAVA8 lambdas expression changes the value of external variables
天蓬老师
天蓬老师 2017-06-12 09:24:10
0
3
979


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)

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
仅有的幸福

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template