Associate final variable to another reference in lambda expression

Asked

Viewed 82 times

2

I was developing a code that uses lambda expressions, where variables outside the scope of the expression should be declared as final. Then the doubt arose: I can associate the variable declared as final to another reference declared within the scope of the expression lambda?

Suppose I have the code below that does not compile:

public void testLambda() {
  ExecutorService executorService = ForkJoinPool.commonPool();
  String nonFinalString = "random";
  // ... outras operacoes aleatorias
  executorService.execute(() -> {
    // erro de compilacao: variavel deve ser final ou "effective final"
    System.out.println(nonFinalString)
  })
}

I could do the following workaround:

public void testLambda() {
  ExecutorService executorService = ForkJoinPool.commonPool();
  String nonFinalString = "random";
  // ... outras operacoes aleatorias
  executorService.execute(() -> {
    // declarar uma nova variavel e associar com a variavel que desejo
    String inScopeString = nonFinalString; 
    System.out.println(nonFinalString)
  })
}

My question is whether the variable declared within the scope inScopeVariable is a variable final or not. The solution proposed above would be considered a bad practice?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.