Skip to content

Instantly share code, notes, and snippets.

@priezz
Last active December 21, 2022 09:42
Show Gist options
  • Save priezz/71300d79dfde1f40314bda5761390163 to your computer and use it in GitHub Desktop.
Save priezz/71300d79dfde1f40314bda5761390163 to your computer and use it in GitHub Desktop.
Pattern matching 6
@sealed
abstract class _CarPart {
Engine(int cylinders, int horsepower);
Transmission(int gears, 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.when(
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: [
CarPart.Engine(cylinders: 6, horsepower: 300),
CarPart.Transmission(gears: 7, isManual: true),
],
).description,
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment