I was developing a code that uses lambda expressions, where variables outside the scope of the expression should be declared as final
. Then the question arose: can I associate the variable declared as final with another declared reference within the scope of the lambda expression?
Let's say 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 final
variable or not. Would the above proposed solution be considered a bad practice?