Skip to content

Instantly share code, notes, and snippets.

@priezz
Created December 21, 2022 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priezz/3ed71d038c334c6ac54e4ba1b3bb8de4 to your computer and use it in GitHub Desktop.
Save priezz/3ed71d038c334c6ac54e4ba1b3bb8de4 to your computer and use it in GitHub Desktop.
Pattern matching 4
class CarPart {
const CarPart();
// METHOD COULD BE GENERATED
T match<T>({
required T Function(Engine v) engine,
required T Function(Transmission v) transmission,
}) {
// ignore_for_file: curly_braces_in_flow_control_structures
if (this is Engine) return engine(this as Engine);
else return transmission(this as Transmission);
}
}
class Engine extends CarPart {
const Engine({
required this.cylinders,
required this.horsepower,
});
final int cylinders;
final int horsepower;
}
class Transmission extends CarPart {
const Transmission({
required this.gears,
required this.isManual,
});
final int gears;
final bool isManual;
}
class Car {
const Car(
this.model, {
required this.parts,
});
final String model;
final List<CarPart> parts;
String get description => [
'These are the parts in a $model:',
for (final part in parts) '- ${_getDescriptionForCarPart(part)}',
'- And a whole bunch of other parts which I was too lazy to mention.',
].join('\n');
}
String _getDescriptionForCarPart(CarPart part) => part.match(
engine: (v) => 'A ${v.cylinders} cylinder engine '
'which makes ${v.horsepower}hp.',
transmission: (v) => 'A ${v.gears} speed '
'${v.isManual ? 'manual' : 'automatic'} transmission.',
);
void main(List<String> args) => print(
const Car(
'Nissan Skyline GT-R',
parts: [
Engine(cylinders: 6, horsepower: 300),
Transmission(gears: 7, isManual: true),
],
).description,
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment