Java: Assign a variable within lambda

前端 未结 4 1916
忘了有多久
忘了有多久 2021-02-08 03:22

I cannot do this in Java:

Optional optStr = Optional.of(\"foo\");
String result;
optStr.ifPresent(s -> result = s);

The doc sa

4条回答
  •  無奈伤痛
    2021-02-08 03:46

    As per Java Specification, lambda gets the variable values as final from the surrounding context as the lambda is passed to that context at runtime.

    The designer of the piece of code which accepts that lambda expression(or Functional Interface) accepts that interface instance\lambda with the faith that its values will not be altered. To strictly make the lambda faithful in this way Java language specification has kept this condition of accessing local context variables as final.

    In short, a lambda is NOT supposed to change the state of the context in which it is invoked.

    You can use an array to capture values, but still it is not advisable and hopefully java will detect and show warnings for such code in future revisions.

提交回复
热议问题