本文介绍了在封闭作用域中定义的局部变量 log 必须是 final 或有效 final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 lambda 和 Java8 的新手.我正面临以下错误.

I'm new to lambda and Java8. I'm facing following error.

在封闭作用域中定义的局部变量 log 必须是 final 或最终有效

public JavaRDD<String> modify(JavaRDD<String> filteredRdd) {

    filteredRdd.map(log -> {

        placeHolder.forEach(text -> {

            //error comes here
            log = log.replace(text, ",");

        });

        return log;

    });

    return null;
}

推荐答案

该消息准确地说明了问题所在:您的变量 log must be final (即:携带关键字 final) 或 be有效地最终(即:您只在 lambda 之外为它分配一个值一次).否则,您不能在 lambda 语句中使用该变量.

The message says exactly what the problem is: your variable log must be final (that is: carry the keyword final) or be effectively final (that is: you only assign a value to it once outside of the lambda). Otherwise, you can't use that variable within your lambda statement.

当然,这与您对 log 的使用相冲突.关键是:你不能从 lambda 内部写入外部的东西......所以你必须退后一步,为你打算做的任何事情寻找其他方法.

But of course, that conflicts with your usage of log. The point is: you can't write to something external from within the lambda ... so you have to step back and look for other ways for whatever you intend to do.

从这个意义上说:只要相信编译器.

In that sense: just believe the compiler.

除此之外,还有一个核心点需要理解:您可以使用可以写入的局部变量.局部变量在运行时被复制"到 lambda 的上下文中,为了实现确定性行为,它们只能被读取,并且应该是常量.

Beyond that, there is one core point to understand: you can not use a local variable that you can write to. Local variables are "copied" into the context of the lambda at runtime, and in order to achieve deterministic behavior, they can only be read, and should be constants.

如果你的用例是写入到某个对象,那么它应该是你封闭类的一个字段,例如!

If your use case is to write to some object, then it should be a field of your enclosing class for example!

所以,长话短说:

  • 局部 在 lambda 中使用(读取)的变量必须像一个常量
  • 你不能写入局部变量!
  • 或者反过来:如果你需要写一些东西,你必须使用你周围类的一个字段(或者提供一个回调方法)
  • local variables used (read) inside a lambda must act like a constant
  • you can not write to local variables!
  • or the other way round: if you need something to write to, you have to use a field of your surrounding class for example (or provide a call back method)

这篇关于在封闭作用域中定义的局部变量 log 必须是 final 或有效 final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 08:29