Polymorphism
suggest changePolymorphism means that one piece of code can work with values of many different types. In Dart it shows up in several forms:
- Subtype polymorphism: a variable of type
Notifiercan hold anEmailNotifieror anSmsNotifier, and calling a method runs the version that belongs to the object's runtime type. - Interface polymorphism: unrelated classes become interchangeable by implementing the same interface or mixing in the same mixin.
- Parametric polymorphism: generic code such as
List<T>orT firstOr<T>(...)is written once and works for every type. - Pattern-based polymorphism: a
switchover asealedclass picks a branch based on the runtime type, with the compiler checking that every case is covered. - Function polymorphism: functions and callable objects with the same signature can be swapped for each other.
Dart does not have method overloading, and extension methods and static members are not polymorphic. This article covers each form, these limits and the workarounds.
For the mechanics of extends, implements and mixins see Inheritance, for @override rules see Overriding, and for generics in depth see Generics.
Subtype polymorphism and dynamic dispatch
Declare the operation on a supertype and let each subtype supply its own implementation. Code that only knows about the supertype then works with every subtype, including ones written later:
abstract class Notifier {
final String recipient;
Notifier(this.recipient);
// Each subtype decides how to deliver.
void send(String message);
// Shared code that calls the polymorphic method.
void sendAll(List<String> messages) {
for (final m in messages) {
send(m);
}
}
}
class EmailNotifier extends Notifier {
EmailNotifier(super.recipient);
@override
void send(String message) => print('email to $recipient: $message');
}
class SmsNotifier extends Notifier {
SmsNotifier(super.recipient);
@override
void send(String message) {
final text = message.length > 20 ? '${message.substring(0, 17)}...' : message;
print('sms to $recipient: $text');
}
}
class PushNotifier extends Notifier {
PushNotifier(super.recipient);
@override
void send(String message) => print('push to $recipient: $message');
}
void main() {
final notifiers = <Notifier>[
EmailNotifier('ann@example.com'),
SmsNotifier('+1 555 0100'),
PushNotifier('device-42'),
];
for (final n in notifiers) {
n.send('Your order has shipped and will arrive Tuesday');
}
print('---');
SmsNotifier('+1 555 0199').sendAll(['Hi', 'Build #812 failed on main branch']);
}
Output:
email to ann@example.com: Your order has shipped and will arrive Tuesday
sms to +1 555 0100: Your order has sh...
push to device-42: Your order has shipped and will arrive Tuesday
---
sms to +1 555 0199: Hi
sms to +1 555 0199: Build #812 failed...
sendAll is written once in Notifier, yet the send it calls is SmsNotifier.send. This is the template method pattern: the base class fixes the algorithm and subclasses fill in the steps.
Static type vs runtime type
Every expression has a static type, known to the compiler, and every object has a runtime type. The static type decides which members you're allowed to call. The runtime type decides which implementation actually runs:
class Animal {
String get sound => '...';
String speak() => 'The ${runtimeType.toString().toLowerCase()} says $sound';
}
class Dog extends Animal {
@override
String get sound => 'woof';
}
class Cat extends Animal {
@override
String get sound => 'meow';
@override
String speak() => '${super.speak()} (and ignores you)';
}
void main() {
Animal a = Dog(); // static type Animal, runtime type Dog
print(a.speak());
a = Cat();
print(a.speak());
Object o = Dog();
print(o.toString()); // Object's toString, Dog doesn't override it
// o.speak(); // error: The method 'speak' isn't defined for the type 'Object'.
print((o as Animal).speak());
}
Output:
The dog says woof
The cat says meow (and ignores you)
Instance of 'Dog'
The dog says woof
Cat.speak extends the inherited behavior with super.speak(), and that inherited speak in turn reads sound, which again dispatches to Cat. Calls through this (explicit or implicit) are always dynamically dispatched; only super.x calls a specific implementation.
Fields are polymorphic too
In Dart a field is accessed through an implicit getter (and setter), so a subclass can override a field with a getter, and code in the superclass that reads the field sees the override:
class Shape {
final String name;
// Fields are accessed through implicit getters, so they're virtual too.
Shape(this.name);
String describe() => 'I am a $name';
}
class Circle extends Shape {
Circle() : super('shape');
@override
String get name => 'circle'; // overrides the field's getter
}
void main() {
final Shape s = Circle();
print(s.name);
print(s.describe());
}
Output:
circle
I am a circle
This differs from Java and C#, where fields are never virtual. Every instance member in Dart (methods, getters, setters, operators and fields) is dispatched on the runtime type, and there is no virtual keyword or final method to opt out (@nonVirtual from package:meta only adds an analyzer warning).
No method overloading
Dart doesn't allow two members with the same name in one class, even if their parameter types differ:
class Printer {
void show(int n) => print('int $n');
void show(String s) => print('string $s');
}
void main() {}
error - ex04.dart:3:8 - The name 'show' is already defined. Try renaming one of the declarations. - duplicate_definition
This is a deliberate design choice: method lookup depends only on the receiver's runtime type and the member name, never on the types of arguments. There are three idiomatic replacements:
- Optional and named parameters cover most overloads that differ only in the number of arguments. See Functions with named parameters.
- Different names for genuinely different operations, as the SDK does with
DateTime.fromMillisecondsSinceEpochandDateTime.parse, orList.addandList.addAll. Named constructors play the role of overloaded constructors; see Constructors. - A wider parameter type plus a type switch when you really want one entry point for several argument types.
class Formatter {
// One method, optional named parameters instead of overloads.
String format(num value, {int decimals = 2, String? unit}) {
final text = value.toStringAsFixed(decimals);
return unit == null ? text : '$text $unit';
}
// One method that switches on the runtime type of its argument.
String describe(Object? value) => switch (value) {
null => 'nothing',
int n when n < 0 => 'negative int $n',
int n => 'int $n',
double d => 'double ${d.toStringAsFixed(1)}',
String s => 'string "$s" (${s.length} chars)',
List(:final length) => 'list of $length',
_ => 'some ${value.runtimeType}',
};
}
void main() {
final f = Formatter();
print(f.format(3.14159));
print(f.format(3.14159, decimals: 4));
print(f.format(72, decimals: 0, unit: 'kg'));
for (final v in [null, -3, 7, 2.75, 'hello', [1, 2, 3], {'a': 1}]) {
print(f.describe(v));
}
}
Output:
3.14
3.1416
72 kg
nothing
negative int -3
int 7
double 2.8
string "hello" (5 chars)
list of 3
some _Map<String, int>
Option 3 trades compile-time checking for flexibility: describe accepts anything, so passing a type you didn't plan for compiles fine and falls into the _ case. Prefer it for formatting, logging and serialization helpers, and prefer separate names elsewhere.
Extension methods are not polymorphic
Extension members are resolved statically, from the static type of the receiver. Overriding doesn't apply to them, so an extension on a subclass is only used when the compiler knows the value has that subclass type:
class Animal {}
class Dog extends Animal {}
extension AnimalLabel on Animal {
String get label => 'some animal';
}
extension DogLabel on Dog {
String get label => 'a dog';
}
void main() {
final dog = Dog();
print(dog.label); // static type Dog: DogLabel is more specific
final Animal sameDog = dog;
print(sameDog.label); // static type Animal: AnimalLabel, even though it's a Dog
final List<Animal> animals = [Dog(), Animal()];
for (final a in animals) {
print(a.label);
}
}
Output:
a dog
some animal
some animal
some animal
The second and third lines print some animal although the object is a Dog. If you need runtime behavior that varies by type, put a real method on the class. When you don't own the class, switch on this inside a single extension:
class Animal {}
class Dog extends Animal {}
extension AnimalLabel on Animal {
// Dispatch on the runtime type manually.
String get label => switch (this) {
Dog() => 'a dog',
_ => 'some animal',
};
}
void main() {
final List<Animal> animals = [Dog(), Animal()];
for (final a in animals) {
print(a.label);
}
}
Output:
a dog
some animal
See Extension methods for more on how extensions are resolved.
Static members are not polymorphic
Static methods and getters belong to the class that declares them. A subclass can declare a static member with the same name, but that only hides it. Code in the superclass keeps calling its own version:
class Parser {
static String get format => 'generic';
// A static method can't be overridden, so this always says 'generic'.
static String describe() => 'parses $format data';
String get name => 'generic';
String info() => 'parser for $name data';
}
class JsonParser extends Parser {
static String get format => 'json'; // hides, doesn't override
@override
String get name => 'json';
}
void main() {
print(Parser.describe());
print(JsonParser.format);
final Parser p = JsonParser();
print(p.info()); // instance getter is overridden
}
Output:
parses generic data
json
parser for json data
Dart also has no way to call a static member through a type parameter (T.create() isn't valid). When generic code needs per-type behavior such as "create a new instance", pass a factory function or an object that provides it. See Static members.
Interface polymorphism
Classes don't need a common superclass with shared code to be interchangeable. It's enough that they implement the same interface. abstract interface class declares a pure contract:
abstract interface class Storage {
void write(String key, String value);
String? read(String key);
}
// Two unrelated implementations; neither inherits any code.
class MemoryStorage implements Storage {
final _data = <String, String>{};
@override
void write(String key, String value) => _data[key] = value;
@override
String? read(String key) => _data[key];
}
class LoggingStorage implements Storage {
final Storage inner;
LoggingStorage(this.inner);
@override
void write(String key, String value) {
print('write $key=$value');
inner.write(key, value);
}
@override
String? read(String key) {
final v = inner.read(key);
print('read $key -> $v');
return v;
}
}
// Code written against the interface works with any implementation.
int bumpCounter(Storage s) {
final n = int.parse(s.read('count') ?? '0') + 1;
s.write('count', '$n');
return n;
}
void main() {
final plain = MemoryStorage();
bumpCounter(plain);
print('plain: ${bumpCounter(plain)}');
final logged = LoggingStorage(MemoryStorage());
bumpCounter(logged);
print('logged: ${bumpCounter(logged)}');
}
Output:
plain: 2
read count -> null
write count=1
read count -> 1
write count=2
logged: 2
bumpCounter doesn't know or care which storage it gets. This is what makes it easy to substitute fakes in tests (see Mocks and test doubles) and to wrap objects in decorators like LoggingStorage (see Composition and delegation). Since every Dart class has an implicit interface, you can also implements an ordinary class; see Implicit interfaces.
Mixins are types too, so a mixin works as a shared interface that comes with default implementations, and classes can still override them:
mixin Describable {
String get name;
String describe() => '$runtimeType "$name"';
}
class Robot with Describable {
@override
final String name;
Robot(this.name);
}
class City with Describable {
@override
final String name;
final int population;
City(this.name, this.population);
@override
String describe() => '${super.describe()}, pop. $population';
}
void main() {
final List<Describable> things = [Robot('R2'), City('Oslo', 709000)];
for (final t in things) {
print(t.describe());
}
}
Output:
Robot "R2"
City "Oslo", pop. 709000
Covariant return types
An override may return a subtype of what the overridden method returns. Callers that know the subclass get the precise type without a cast, while callers that only know the superclass still work:
class Document {
final String title;
Document(this.title);
Document copy() => Document(title);
}
class Invoice extends Document {
final int amount;
Invoice(super.title, this.amount);
// Covariant return type: narrower than Document, still a valid override.
@override
Invoice copy() => Invoice(title, amount);
}
void main() {
final inv = Invoice('INV-7', 250);
final c = inv.copy(); // static type Invoice, no cast needed
print('${c.title} ${c.amount}');
final Document d = inv;
final dc = d.copy(); // static type Document, runtime type Invoice
print(dc.runtimeType);
}
Output:
INV-7 250
Invoice
Parameters go the other way: an override may widen a parameter type but not narrow it, unless the parameter is marked covariant (see Overriding).
Polymorphic operators and toString
Operators are ordinary instance methods with special syntax, so they're dispatched the same way. toString, == and hashCode are declared on Object, which means code like print, string interpolation, join, Set and Map can call them on any object and get your override:
class Money {
final int cents;
const Money(this.cents);
Money operator +(Money other) => Money(cents + other.cents);
Money operator *(int factor) => Money(cents * factor);
@override
String toString() => '\$${(cents / 100).toStringAsFixed(2)}';
}
class Vec {
final double x, y;
const Vec(this.x, this.y);
Vec operator +(Vec other) => Vec(x + other.x, y + other.y);
@override
String toString() => 'Vec($x, $y)';
}
void main() {
final price = const Money(1999) * 3 + const Money(500);
print('total: $price'); // string interpolation calls toString()
print(const Vec(1, 2) + const Vec(0.5, 0.5));
// print, join and interpolation call toString() polymorphically on anything.
final List<Object> mixed = [price, const Vec(3, 4), 42, true];
print(mixed.join(' | '));
}
Output:
total: $64.97
Vec(1.5, 2.5)
$64.97 | Vec(3.0, 4.0) | 42 | true
Overriding == correctly has a few traps (it must be paired with hashCode, and it takes an Object parameter). See Equality and comparison.
Calling overridden methods from a constructor
Because dispatch always uses the runtime type, a superclass constructor that calls an overridable method runs the subclass version, before the subclass constructor has finished. Dart initializes fields in a fixed order, so it's important to know what's already set:
class Widget {
Widget() {
// Calls the subclass override before the subclass constructor body runs.
print('Widget() sees: ${label()}');
}
String label() => 'widget';
}
class Button extends Widget {
final String text; // set by the initializing formal, before Widget() runs
String state = 'idle'; // field initializer, also runs before Widget()
int clicks;
Button(this.text) : clicks = 0 {
clicks = 10; // constructor body: runs after Widget()
}
@override
String label() => 'button "$text" ($state, $clicks clicks)';
}
void main() {
final b = Button('OK');
print('after construction: ${b.label()}');
}
Output:
Widget() sees: button "OK" (idle, 0 clicks)
after construction: button "OK" (idle, 10 clicks)
Initializing formals (this.text), field initializers (state = 'idle') and the initializer list (clicks = 0) all run before the superclass constructor body, so the override sees them. Assignments in the subclass constructor body run after, so the override sees the old value (0, not 10). Unlike Java, a non-nullable field can never be observed as null here; a late field that hasn't been assigned yet throws a LateInitializationError instead. The safest rule is still to avoid calling overridable methods from constructors.
Parametric polymorphism with generics
Generics make code polymorphic over types without any class hierarchy: the same implementation works for int, String or your own classes, and the compiler keeps track of the precise type. A bound (T extends Comparable<T>) restricts T to types that support the operations you need:
// Parametric polymorphism: one implementation for every type T.
T firstOr<T>(List<T> items, T fallback) => items.isEmpty ? fallback : items.first;
class Box<T> {
final T value;
Box(this.value);
Box<R> map<R>(R Function(T) f) => Box(f(value));
@override
String toString() => 'Box<$T>($value)';
}
// Bounded: works for any T that is Comparable to itself.
T maxOf<T extends Comparable<T>>(Iterable<T> items) {
var best = items.first;
for (final item in items.skip(1)) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
void main() {
print(firstOr([3, 1, 2], 0));
print(firstOr(<String>[], 'none'));
final b = Box(21).map((n) => n * 2).map((n) => 'answer: $n');
print(b);
print(maxOf([3, 9, 4]));
print(maxOf(['pear', 'apple', 'zucchini', 'fig']));
print(maxOf([DateTime(2024, 5, 1), DateTime(2026, 1, 1)]).year);
}
Output:
3
none
Box<String>(answer: 42)
9
zucchini
2026
Note that maxOf([3, 9, 4]) infers T as num, because int implements Comparable<num>, not Comparable<int>. That's why maxOf uses a loop instead of items.reduce(...): reduce on a List<int> would reject a callback typed (num, num) => num at runtime. Generics explains this covariance in detail.
Function polymorphism and callable objects
Functions are objects with types such as double Function(double). Any function with a compatible signature, whether a top-level function, a closure or a method tear-off, can be passed where that type is expected. A class with a call method can be invoked like a function and torn off to a function value, so stateful strategies fit in the same slot:
typedef Discount = double Function(double price);
double tenPercentOff(double price) => price * 0.9;
// A callable class: any object with a call() method can be used like a function.
class BulkDiscount {
final double threshold;
final double off;
const BulkDiscount(this.threshold, this.off);
double call(double price) => price >= threshold ? price - off : price;
}
double checkout(double price, Discount discount) => discount(price);
void main() {
final discounts = <String, Discount>{
'none': (p) => p,
'ten percent': tenPercentOff,
'bulk': const BulkDiscount(100, 15).call,
};
for (final MapEntry(:key, :value) in discounts.entries) {
print('$key: ${checkout(120, value)} ${checkout(80, value)}');
}
const bulk = BulkDiscount(100, 15);
print(bulk(250)); // call() invoked implicitly
Discount d = bulk; // implicit tear-off of .call
print(d(50));
}
Output:
none: 120.0 80.0
ten percent: 108.0 72.0
bulk: 105.0 80.0
235.0
50.0
For a single operation this is often lighter than defining an interface with one method. See Lambdas and closures.
Pattern matching on sealed classes
Methods put the behavior in each class. The alternative is to put it in a function that switches on the type. With a sealed class the compiler knows every direct subtype and checks that the switch handles them all:
sealed class Expr {}
class Num extends Expr {
final int value;
Num(this.value);
}
class Add extends Expr {
final Expr left, right;
Add(this.left, this.right);
}
class Mul extends Expr {
final Expr left, right;
Mul(this.left, this.right);
}
int eval(Expr e) => switch (e) {
Num(:final value) => value,
Add(:final left, :final right) => eval(left) + eval(right),
Mul(:final left, :final right) => eval(left) * eval(right),
};
String show(Expr e) => switch (e) {
Num(:final value) => '$value',
Add(:final left, :final right) => '(${show(left)} + ${show(right)})',
Mul(:final left, :final right) => '${show(left)} * ${show(right)}',
};
void main() {
final e = Mul(Add(Num(2), Num(3)), Num(4));
print('${show(e)} = ${eval(e)}');
}
Output:
(2 + 3) * 4 = 20
The two styles have opposite trade-offs, known as the expression problem:
| Abstract methods | sealed class + switch |
|
|---|---|---|
| Adding a new type | Easy: write one class, no other code changes | Every switch must get a new case (the compiler tells you which) |
| Adding a new operation | Every class must implement it | Easy: write one new function |
| Subtypes in other libraries | Allowed | Not allowed: a sealed hierarchy is closed |
| Behavior lives | Next to the data | In one place per operation |
Use methods when the set of types is open (plugins, user extensions, platform implementations). Use sealed when the set of types is fixed and you expect to add operations: AST nodes, UI states, results, events and protocol messages. See Pattern matching for the full pattern syntax.
Avoid a third style, chains of if (x is A) ... else if (x is B) ... over a non-sealed hierarchy, or a switch with a default case. They compile even when a new subtype is added and silently fall through to the default.
Double dispatch
Dart is single dispatch: only the receiver's runtime type selects the implementation, never the arguments' types. When behavior depends on the runtime types of two objects (collisions in a game, converting between units, combining two values), switch on a record of both:
sealed class Shape {}
class Circle extends Shape {}
class Square extends Shape {}
// The pair of runtime types picks the case: double dispatch with one switch.
String collide(Shape a, Shape b) => switch ((a, b)) {
(Circle(), Circle()) => 'circle hits circle: bounce',
(Square(), Square()) => 'square hits square: stack',
(Circle(), Square()) || (Square(), Circle()) => 'circle hits square: roll off',
};
void main() {
final shapes = <Shape>[Circle(), Square()];
for (final a in shapes) {
for (final b in shapes) {
print(collide(a, b));
}
}
}
Output:
circle hits circle: bounce
circle hits square: roll off
circle hits square: roll off
square hits square: stack
Add a Triangle subclass and the analyzer immediately reports the missing combinations:
error - ex09b.dart:10:37 - The type '(Shape, Shape)' isn't exhaustively matched by the switch cases since it doesn't match the pattern '(Circle(), Triangle())'. Try adding a wildcard pattern or cases that match '(Circle(), Triangle())'. - non_exhaustive_switch_expression
Before Dart 3 added patterns, the standard answer was the visitor pattern: each node's accept method calls the visitor method for its own type, so two virtual calls together dispatch on both the node and the visitor. You'll still see it in packages such as analyzer, and it's useful when the hierarchy can't be sealed:
// Classic visitor: each node calls back the visitor method for its own type.
abstract interface class ExprVisitor<R> {
R visitNum(Num n);
R visitAdd(Add a);
R visitMul(Mul m);
}
abstract class Expr {
R accept<R>(ExprVisitor<R> v);
}
class Num extends Expr {
final int value;
Num(this.value);
@override
R accept<R>(ExprVisitor<R> v) => v.visitNum(this);
}
class Add extends Expr {
final Expr left, right;
Add(this.left, this.right);
@override
R accept<R>(ExprVisitor<R> v) => v.visitAdd(this);
}
class Mul extends Expr {
final Expr left, right;
Mul(this.left, this.right);
@override
R accept<R>(ExprVisitor<R> v) => v.visitMul(this);
}
class Evaluator implements ExprVisitor<int> {
@override
int visitNum(Num n) => n.value;
@override
int visitAdd(Add a) => a.left.accept(this) + a.right.accept(this);
@override
int visitMul(Mul m) => m.left.accept(this) * m.right.accept(this);
}
class Printer implements ExprVisitor<String> {
@override
String visitNum(Num n) => '${n.value}';
@override
String visitAdd(Add a) => '(${a.left.accept(this)} + ${a.right.accept(this)})';
@override
String visitMul(Mul m) => '${m.left.accept(this)} * ${m.right.accept(this)}';
}
void main() {
final Expr e = Mul(Add(Num(2), Num(3)), Num(4));
print('${e.accept(Printer())} = ${e.accept(Evaluator())}');
}
Output:
(2 + 3) * 4 = 20
Duck typing with dynamic
If two classes have a method with the same name but no common supertype, the static type system won't let you call it through anything but dynamic. Calls on dynamic are looked up by name at runtime:
class Duck {
String quack() => 'Quack!';
}
class Robot {
String quack() => 'beep QUACK beep';
}
void main() {
// No shared supertype besides Object, so only dynamic lets us call quack().
final List<dynamic> things = [Duck(), Robot(), 'not a duck'];
for (final t in things) {
try {
print(t.quack());
} on NoSuchMethodError catch (e) {
print('error: ${e.toString().split('\n').first}');
}
}
}
Output:
Quack!
beep QUACK beep
error: NoSuchMethodError: Class 'String' has no instance method 'quack'.
This works, but you lose autocompletion and compile-time checks, and a typo becomes a runtime NoSuchMethodError. Calls through dynamic are also slower, and they force the compiler to keep every method with that name, which defeats tree shaking. Prefer introducing an interface (or an extension type wrapper) and reach for dynamic only at boundaries, such as decoded JSON.
Summary
- Every instance member, fields included, is dispatched on the runtime type. The static type only decides what you're allowed to call.
- Calls through
thisare dynamic;super.membercalls the superclass implementation. - Dart has no overloading. Use optional or named parameters, different names, named constructors, or one method with a type
switch. - Extension methods and static members are resolved at compile time and are never polymorphic.
- Overrides may narrow return types and widen parameter types.
- A superclass constructor that calls an overridable method sees subclass fields set by initializers, but not those set in the subclass constructor body.
- Generics give polymorphism over types; function types and callable classes give polymorphism over behavior.
- For a closed set of types, a
sealedclass with exhaustiveswitchis often clearer than abstract methods, and aswitchon a record handles double dispatch. - Use
dynamicduck typing only when you have no better option.