dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
636 stars 170 forks source link

rule type_literal_in_constant_pattern in switch cases #4791

Open Fernandomr88 opened 1 year ago

Fernandomr88 commented 1 year ago

so I have a function that basically is this

get<T>() {
 switch(T) {
  case Person:
   //code
  case Dog:
   //code
  }
}

which is called like get<Person>();

and by using the notation suggested by this rule (Person _), it does not work.

How am I supposed to change my code to be adequate to this linter rule?

Originally posted by @Fernandomr88 in https://github.com/dart-lang/lints/issues/117#issuecomment-1775789382

devoncarew commented 1 year ago

From @bwilkerson on the original (closed) issue:

It sounds like the rule might need to be changed to not produce a diagnostic if the value being switched over is Type.

lrhn commented 1 year ago

I'd still recommend changing to one of:

Now that type patterns exist, it's easy to misread case Person: as doing a type check against Person.

And I'd not make exceptions in the lint.

Fernandomr88 commented 1 year ago

I'd still recommend changing to one of:

  • case const Person:, or
  • case == Dog:

Now that type patterns exist, it's easy to misread case Person: as doing a type check against Person.

And I'd not make exceptions in the lint.

case const Person: doesnt work case == Dog: works

but the suggestion made by the linter is either case const (Person) or case Person _, and both doesn't work for this case

lrhn commented 1 year ago

This is a false positive for the lint, which suggests that you intended what would be case Person() or case Person _.

The workaround, to avoid getting that false positive, is case == Person or case const (Person) - and sadly the parentheses are needed - which both compares Type objects for equality.

The documentation should probably explain this.

I don't want to disable the lint if we can see that you are switching on Type objects. Even in that case, it's better to move to == Person as the pattern, because it's more readable.