Description
The primary constructors proposal (#3023) says:
In the case where the constructor is constant, and in the case where the declaration is an inline class or an enum declaration, the modifier
final
on every instance variable is required. Hence, it can be omitted from the formal parameter in the primary constructor:This mechanism follows an existing pattern, where
const
modifiers can be omitted in the case where the immediately syntactic context implies that this modifier must be present. For example,const [const C()]
can be written asconst [C()]
. In the examples above, the parameter-and-variable declarationsfinal int x
andfinal int y
are written asint x
andint y
, and this is allowed because it would be a compile-time error to omit final in an inline class, and in a class with a constant constructor. In other words, when we see inline on the class or const on the class name, we know that final is implied on all instance variables.
I'm a little worried about the implicit magic here, but I think the argument makes sense. The brevity is certainly nice.
However, I find the inconsistency with field declarations worrisome. If we really think it makes sense to elide final
on parameters in primary constructors on inline classes, shouldn't also allow eliding final
on field declarations in inline classes and enums too? The argument seems to equally well to them.
Why not let you write:
enum E {
one('a'),
two('b');
String s; // <- No `final` needed.
const E(this.s);
}
Whichever way we decide to go, I think primary constructors should probably be consistent with field declarations.