Skip to main content

prefer-switch-with-sealed-classes

added in: 1.17.0

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;

if (value is Car || value is Truck) {} // LINT
if (value case Car() || Truck()) {} // LINT
}

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():
...
}
}

sealed class Vehicle {}

class Car extends Vehicle {}

class Truck implements Vehicle {
const Truck();
}