Description
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.