Try with resource why cannot modify resource

e2rabi :

I found a try with resources example that doesn't compile when I try to set the value of the reference scan to null

try(Scanner scan = new Scanner(System.in)) {
    String s = scan.nextLine();
    System.out.println(s);
    scan = null;
}

I ask what's the rule behind this compilation error , I did some search on the net but i didn't find a rule that explain it Thanks for any explanation : =)

Andrew Tobilko :

It's by design. You can't reassign a final variable.

14.20.3. try-with-resources

A variable declared in a resource specification is implicitly declared final if it is not explicitly declared final (§4.12.4).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305748&siteId=1