search

Home  >  Q&A  >  body text

java-ee - JAVA8 lambdas expression changes the value of external variables


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)

天蓬老师天蓬老师2764 days ago984

reply all(3)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-12 09:26:10

    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.

    reply
    0
  • 欧阳克

    欧阳克2017-06-12 09:26:10

    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.

    reply
    0
  • 怪我咯

    怪我咯2017-06-12 09:26:10

    Final, of course, immutable. If you must change, don’t use lambda. If you use lambda, don’t modify the value

    reply
    0
  • Cancelreply