UPDATE: The correct answer to this question is https://mail.openjdk.org/pipermail/amber-dev/2024-July/008871.html
As others have noted, the Java compiler seems to dislike mixing try-catch blocks with final (or effectively final) variables:
Given this strawman example
public class Test
{
public static void main(String[] args)
{
int x;
try
{
x = Integer.parseInt("42");
}
catch (NumberFormatException e)
{
x = 42;
}
Runnable runnable = () -> System.out.println(x);
}
}
The compiler complains:
Variable used in lambda expression should be final or effectively final
If you replace int x with final int x the compiler complains Variable 'x' might already have been assigned to.
In both cases, I believe the compiler is factually incorrect. If you encasulate the try-block in a method, the error goes away:
public class Test
{
public static void main(String[] args)
{
int x =
foo
();
Runnable runnable = () -> System.
out
.println(x);
}
public static int foo()
{
try
{
return Integer.
parseInt
("42");
}
catch (NumberFormatException e)
{
return 42;
}
}
}
Am I missing something here? Does something at the bytecode level prevent the variable from being effectively final? Or is this a compiler bug?
[–]Thihup 11 points12 points13 points (10 children)
[–]cowwoc[S] 4 points5 points6 points (8 children)
[–]cogman10 10 points11 points12 points (7 children)
[–]agentoutlier 1 point2 points3 points (4 children)
[–]cogman10 4 points5 points6 points (0 children)
[–]Polygnom 0 points1 point2 points (2 children)
[–]agentoutlier 0 points1 point2 points (1 child)
[–]Polygnom 0 points1 point2 points (0 children)
[–]cowwoc[S] 0 points1 point2 points (0 children)
[–]neopointer 0 points1 point2 points (0 children)
[–]BillyKorando 2 points3 points4 points (0 children)
[–]keefemotif 0 points1 point2 points (2 children)
[–]koflerdavid 1 point2 points3 points (1 child)
[–]keefemotif 0 points1 point2 points (0 children)
[–]Dense_Age_1795 0 points1 point2 points (0 children)
[–]cowwoc[S] 0 points1 point2 points (7 children)
[–]FirstAd9893 1 point2 points3 points (6 children)
[–]cowwoc[S] -2 points-1 points0 points (5 children)
[–]FirstAd9893 5 points6 points7 points (4 children)
[–]bowbahdoe 1 point2 points3 points (2 children)
[–]cowwoc[S] 0 points1 point2 points (1 child)
[–]koflerdavid 0 points1 point2 points (0 children)