Skip to content

Should we allow eliding final on field declarations in enums and inline classes? #3171

Open
@munificent

Description

@munificent

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 as const [C()]. In the examples above, the parameter-and-variable declarations final int x and final int y are written as int x and int 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    brevityA feature whose purpose is to enable concise syntax, typically expressible already in a longer formprimary-constructors

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions