Local variable log defined in an enclosing scope must be final or effectively final

Balaji Reddy :

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

Local variable log defined in an enclosing scope must be final or effectively 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;
}
GhostCat salutes Monica C. :

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.

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.

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!

So, long story short:

  • 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)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=448029&siteId=1