Dart Sealed Classes
Dart Sealed Classes
A sealed class is a class with a fixed list of subclasses.
You create one with the sealed keyword before class.
All the direct subclasses must be written in the same file as the sealed class, so Dart knows every one of them:
Example
sealed class Shape {}
class Circle extends Shape {
final double radius;
Circle(this.radius);
}
class Square extends Shape {
final double side;
Square(this.side);
}
void main() {
Shape a = Circle(2);
Shape b = Square(3);
print(a is Circle);
print(b is Square);
}
Try it Yourself »
Result:
true
true
In this example, a Shape is always a Circle or a Square, and nothing else.
A sealed class is also abstract, so you cannot create an object of the sealed class itself:
Example
sealed class Shape {}
class Circle extends Shape {}
void main() {
var s = Shape();
print(s);
}
Try it Yourself »
Result:
main.dart:6:11: Error: The class 'Shape' is abstract and can't be instantiated.
var s = Shape();
^^^^^
Exhaustive Switch
The big advantage of a sealed class is in switch expressions.
Because Dart knows all the subclasses, it can check that a switch handles every one of them.
You do not need a _ case:
Example
sealed class Shape {}
class Circle extends Shape {
final double radius;
Circle(this.radius);
}
class Square extends Shape {
final double side;
Square(this.side);
}
double area(Shape shape) {
return switch (shape) {
Circle c => 3.14 * c.radius * c.radius,
Square s => s.side * s.side,
};
}
void main() {
print(area(Circle(2)));
print(area(Square(3)));
}
Try it Yourself »
Result:
12.56
9.0
The case Circle c matches when the shape is a Circle, and puts it in the variable c with the type Circle.
That is why you can use c.radius in the result.
You can also use object patterns to get the fields directly:
Example
sealed class Shape {}
class Circle extends Shape {
final double radius;
Circle(this.radius);
}
class Square extends Shape {
final double side;
Square(this.side);
}
String describe(Shape shape) {
return switch (shape) {
Circle(:var radius) => 'A circle with radius $radius',
Square(:var side) => 'A square with side $side',
};
}
void main() {
print(describe(Circle(2)));
print(describe(Square(3)));
}
Try it Yourself »
Result:
A circle with radius 2.0
A square with side 3.0
A Missing Case Is an Error
Now, let us add a new subclass, Triangle, but forget to handle it in the switch.
Dart finds the problem before the program runs, and shows which type is missing:
Example
sealed class Shape {}
class Circle extends Shape {
final double radius;
Circle(this.radius);
}
class Square extends Shape {
final double side;
Square(this.side);
}
class Triangle extends Shape {
final double base;
final double height;
Triangle(this.base, this.height);
}
double area(Shape shape) {
return switch (shape) {
Circle c => 3.14 * c.radius * c.radius,
Square s => s.side * s.side,
};
}
void main() {
print(area(Circle(2)));
}
Try it Yourself »
Result:
main.dart:20:18: Error: The type 'Shape' is not exhaustively matched by the switch cases since it doesn't match 'Triangle()'.
- 'Shape' is from 'main.dart'.
Try adding a wildcard pattern or cases that match 'Triangle()'.
return switch (shape) {
^
This is very helpful in big programs.
When you add a new subclass, Dart shows you every switch that you need to update.
Add the missing case, and the program runs again:
Example
sealed class Shape {}
class Circle extends Shape {
final double radius;
Circle(this.radius);
}
class Square extends Shape {
final double side;
Square(this.side);
}
class Triangle extends Shape {
final double base;
final double height;
Triangle(this.base, this.height);
}
double area(Shape shape) {
return switch (shape) {
Circle c => 3.14 * c.radius * c.radius,
Square s => s.side * s.side,
Triangle t => t.base * t.height / 2,
};
}
void main() {
print(area(Circle(2)));
print(area(Square(3)));
print(area(Triangle(4, 5)));
}
Try it Yourself »
Result:
12.56
9.0
10.0
Sealed vs Abstract
With a normal abstract class, anyone can add a new subclass in another file, so Dart can never know all the subclasses.
That is why a switch over an abstract class needs a _ case, even when you have handled every subclass you wrote:
Example
abstract class Shape {}
class Circle extends Shape {}
class Square extends Shape {}
String name(Shape shape) {
return switch (shape) {
Circle() => 'Circle',
Square() => 'Square',
};
}
void main() {
print(name(Circle()));
}
Try it Yourself »
Result:
main.dart:8:18: Error: The type 'Shape' is not exhaustively matched by the switch cases since it doesn't match 'Shape()'.
- 'Shape' is from 'main.dart'.
Try adding a wildcard pattern or cases that match 'Shape()'.
return switch (shape) {
^
Change abstract to sealed, and the same switch works.
A Real-World Example
Sealed classes are often used for results that can be one of a few cases, like a payment that either succeeds or fails:
Example
sealed class PaymentResult {}
class Success extends PaymentResult {
final double amount;
Success(this.amount);
}
class Failure extends PaymentResult {
final String reason;
Failure(this.reason);
}
PaymentResult pay(double amount, double balance) {
if (amount > balance) {
return Failure('Not enough money');
}
return Success(amount);
}
void main() {
for (var amount in [20.0, 500.0]) {
var message = switch (pay(amount, 100)) {
Success(:var amount) => 'Paid $amount',
Failure(:var reason) => 'Payment failed: $reason',
};
print(message);
}
}
Try it Yourself »
Result:
Paid 20.0
Payment failed: Not enough money
Remember: Use a sealed class when you know all the possible subtypes, and you want Dart to check that your code handles each one.