Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in java, why do closured variables need to be declared final?

final Object o;

List l = new ArrayList(){{
    // closure over o, in lexical scope
    this.add(o);
}};

why must o be declared final? why don't other JVM languages with mutable vars have this requirement?

like image 718
Dustin Getz Avatar asked Mar 05 '26 10:03

Dustin Getz


1 Answers

This is not JVM-deep, it all happens at syntactic-sugar level. The reason is that exporting a non-final var via a closure makes it vulnerable to datarace issues and, since Java was designed to be a "blue-collar" language, such a surprising change in the behavior of an otherwise tame and safe local var was deemed way too "advanced".

like image 108
Marko Topolnik Avatar answered Mar 07 '26 07:03

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!