You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What this means is that saying “static fields are initialized first” can easily be subverted, and the fact is not blatantly visible in the code. It is one of those things where you need to read the whole class to find out in which order things will run.
Given how the two kinds of initialization code live in the same lexical space, it would be much better if initialization would also proceed linearly, following the lexical structure. One possibility to do this would be to have the static initializer block run the whole thing and compute the values to be put into all fields of the MODULE instance, and then these values are passed in as constructor arguments. The down-side would be that “this” is not available. I’d rather have this restriction (and require a @static annotation on the object itself) than erratic initialization order changes (which might not even be known at compile time). Semantics of a missing @static annotation on the object could then be to run the whole initialization within the MODULE constructor, giving you “this” but taking away finality of static fields.
The text was updated successfully, but these errors were encountered:
The thing here is that there is no way to get it “right” in this case, because the initialization code of the “final” (only not in bytecode) “val i” runs outside of the context of class initialization. Given that it cannot work, this must be a compile time error.
What this means is that saying “static fields are initialized first” can easily be subverted, and the fact is not blatantly visible in the code. It is one of those things where you need to read the whole class to find out in which order things will run.
Given how the two kinds of initialization code live in the same lexical space, it would be much better if initialization would also proceed linearly, following the lexical structure. One possibility to do this would be to have the static initializer block run the whole thing and compute the values to be put into all fields of the MODULE instance, and then these values are passed in as constructor arguments. The down-side would be that “this” is not available. I’d rather have this restriction (and require a @static annotation on the object itself) than erratic initialization order changes (which might not even be known at compile time). Semantics of a missing @static annotation on the object could then be to run the whole initialization within the MODULE constructor, giving you “this” but taking away finality of static fields.
The text was updated successfully, but these errors were encountered: