首页 > 解决方案 > Set a local variable value from inside a lambda

问题描述

I have the following code:

  public void visitStrAttribute(String attributeName, Consumer<String> attributeConsumer) {
    IntConsumer intConsumer;
    int stringByteArrayLength = 0;
    visitIntAttribute("", (IntValue) -> stringByteArrayLength = IntValue);
    attributeConsumer
        .accept(new String(readInputStream(stringByteArrayLength), StandardCharsets.UTF_8));
  }

I need to set stringByteArrayLength inside the lambda but an error message appears and it told me Local variable stringByteArrayLength defined in an enclosing scope must be final or effectively final.

How do I fix this?

标签: javalambdascope

解决方案


一种解决方案是使您的变量成为具有一个元素的最终数组,并修改其中的元素,如下所示:

final int[] stringByteArrayLength = {0};
visitIntAttribute("", (IntValue) -> stringByteArrayLength[0] = IntValue);

尽管我不认为这是最佳实践。我宁愿返回一个新的更改值而不是更改它。


推荐阅读