Skip to main content

prefer-switch-with-sealed-classes

added in: 1.17.0
Pro+

Suggests to use a switch statement or expression instead of conditionals with sealed class instances.

When it comes to sealed classes, the analyzer warns you when a new class is not covered by a switch case. This feature is not available for if statements and conditional expressions. Therefore using switches where possible can reduce the number of potential bugs.

Example

❌ Bad:

void fn() {
final Vehicle? value;

// LINT: Prefer switch statement/expression when checking sealed classes.
if (value is Car || value is Truck) {}

// LINT: Prefer switch statement/expression when checking sealed classes.
if (value case Car() || Truck()) {}
}

sealed class Vehicle {}

class Car extends Vehicle {}

class Truck implements Vehicle {
const Truck();
}

✅ Good:

void fn() {
final Vehicle? value;

switch (value) {
case Car():
...

case Truck():
...
}
}