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?