Skip to content

Make prefer_collection_literals less suggestive for LinkedHashMap and LinkedHashSet #57993

@jamesderlin

Description

@jamesderlin

I have code where insertion order is important, and even though Map's default implementation is a LinkedHashMap, I'd like to emphasize this in code by explicitly using LinkedHashMap:

final lruCache = LinkedHashMap<String, Stuff>();

This triggers the prefer_collection_literals lint.

I thought maybe I instead could do:

final LinkedHashMap<String, Stuff> lruCache = {};

but that runs afoul of --no-implicit-dynamic. I thought that I could give in and be redundant:

final LinkedHashMap<String, Stuff> lruCache = <String, Stuff>{};

but that doesn't work either:

error • A value of type 'Map<String, Stuff>' can't be assigned to a variable of type 'LinkedHashMap<String, Stuff>' at ... • invalid_assignment

So I think that there's no way for me to actually initialize a type declared as a LinkedHashMap while appeasing the linter.

I think that prefer_collection_literals should ignore LinkedHashMap (and LinkedHashSet). In #57905, @bwilkerson asked:

I'd like to drop the flagging of:

  1. LinkedHashSet constructors altogether, and

I'm not sure why. As I understand it, a set literal creates an instance of LinkedHashSet, so the two should be consistent.

I claim that if someone is explicitly using LinkedHashMap/LinkedHashSet instead of just Map or Set, then they care about being explicit. (And if we don't think that's important, then I'd argue that LinkedHashMap and LinkedHashSet shouldn't even exist as separate classes.)

Metadata

Metadata

Assignees

Labels

P3A lower priority bug or feature requestdevexp-linterIssues with the analyzer's support for the linter packagelegacy-area-analyzerUse area-devexp instead.linter-set-recommended

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions