Skip to content

Instantly share code, notes, and snippets.

@swavkulinski
Last active May 23, 2023 07:14
Show Gist options
  • Save swavkulinski/9ac85032b48d824611ce96e41f13e0a4 to your computer and use it in GitHub Desktop.
Save swavkulinski/9ac85032b48d824611ce96e41f13e0a4 to your computer and use it in GitHub Desktop.
Dart sealed class
void main() {
f(A1('1'));
f(A2(2));
// f(A3()); // Abstract classes cannot be instantiated
f(A31('A3',31));
f(A32('A3',32));
f(A33('A3','33'));
}
void f(A x) {
final r = switch (x) {
A1() => 'x = ${x.x}',
A2(:var y) => 'y = $y',
A31(:var a, :var e) => 'super type = $e, a = $a',
A33(:var c, :var e) => 'super type = $e, c type = ${c.runtimeType}, c = $c',
// default for all other A3 subtypes (A32)
A3() => 'x is some other A3 type'
};
print('runtime: ${x.runtimeType} unboxing: $r');
}
// root sealed class
sealed class A {}
// subtype of A
class A1 extends A {
final String x;
A1(this.x);
}
// another subtype of A
class A2 extends A {
final int y;
A2(this.y);
}
// subtype of A which is a sealed class of other subclasses
sealed class A3 extends A {
final String e;
A3(this.e);
}
// subtype of A3
class A31 extends A3 {
final int a;
A31(super.e, this.a);
}
// another subtype of A3
class A32 extends A3 {
final int b;
A32(super.e, this.b);
}
// subtype of A3 with generic parameter
class A33<T> extends A3 {
final T c;
A33(super.e, this.c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment