Search code examples
javalambdafunctional-programmingfinal

Java: why java can't automatically "finalize" local variables in enclosing scope of lambda expression?


I understand this as a standard part of functional programming.. my question is to why the compiler cannot automatically declare a copy of the variable as final just before the lambda statement begins?

import java.util.stream.IntStream;

public class Example
{
  public static void main( String args[] )
  {
    int i = 5;
    i = 6;
    IntStream.range(0, 10).mapToLong( j-> i * j ).sum();
  }


}

fails... with "Local variable i defined in an enclosing scope must be final or effectively final" whereas it seems the compiler should be smart enough to do something like this

import java.util.stream.IntStream;

public class Example
{
  public static void main( String args[] )
  {
    int i = 5;
    i = 6;
    final int _i = i;
    IntStream.range(0, 10).mapToLong( j-> _i * j ).sum();
  }


}

the compiler could enforce that the finalized variable is never modified by the lambda function


Solution

  • Well, the compiler would actually do it if your variable i were effectively final.

      public static void main( String args[] )
      {
        int i = 5;
        IntStream.range(0, 10).mapToLong( j-> i * j ).sum();
      }
    

    However with the second assignment i = 6; you're making it not "effectively final", you're indicating that you actually want it to be mutable.

    So why in this case should the compiler make a final copy of your variable despite you signalling that you want it to be mutable?