Skip to content

Exclude switch expression cases from prefer_final_locals lint #59710

Open
@jodinathan

Description

@jodinathan

The prefer_final_locals lint currently triggers warnings for variables declared within switch expression cases. This behavior can lead to unnecessary boilerplate or awkward refactoring, as the cases often represent one-off usage patterns where the enforcement of final adds no clear benefit.

Example

return switch (val) {
  Enum en => () {
    assert(Queryable.words.containsKey(en.name));
    return Queryable.words[en.name];
  }(),
  bool b => b ? 1 : 0,
  _ => val,
};

In this example, the lint suggests making en and b final. However, these variables are implicit, context-specific, and short-lived, making the suggestion less meaningful. Forcing developers to ignore the lint in these scenarios is counterproductive.

Proposed Solution
Update the prefer_final_locals lint to exclude variables implicitly declared within switch expression cases. This would align the lint's behavior with practical usage patterns and avoid unnecessary warnings.

Benefits
Improves developer experience by avoiding irrelevant lint warnings.
Maintains code clarity and reduces the need for lint overrides.
Encourages adoption of switch expressions without friction.

Additional Context
This behavior is similar to how final enforcement is not applied to loop variables in for or forEach constructs, where implicit, short-lived variables are common.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P4area-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-linterIssues with the analyzer's support for the linter packagelinter-false-positiveIssues related to lint rules that report a problem when it isn't a problem.type-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions