|
|
|
|
|
by munificent
1288 days ago
|
|
Extension methods (which Dart also supports) are orthogonal to the pattern matchinng going on here. If you wanted to define that example function as an extension method, you could: extension on Shape {
double calculateArea() => switch (this) {
Square(length: var l) => l * l,
Circle(radius: var r) => math.pi * r * r
};
}
example(Shape someShape) {
print(someShape.calculateArea();
}
Extension methods are statically dispatched, so they don't give you any way to write code that's polymorphic over the various subtypes. In order to have code specific to each subtype you need something like virtual methods (which requires you to be able to add methods directly to those classes) or type switches (as in the pattern matching like we have here). |
|