Created with <3 with dartpad.dev.
Last active
December 20, 2022 23:51
-
-
Save priezz/7359a4891163dc55d3f96f4d819429ed to your computer and use it in GitHub Desktop.
Pattern matching 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CarPart { | |
const CarPart(this.type); | |
final CarPartType type; | |
} | |
enum CarPartType<T extends CarPart> { | |
engine<Engine>(), | |
transmission<Transmission>(), | |
} | |
class Engine extends CarPart { | |
const Engine({ | |
required this.cylinders, | |
required this.horsepower, | |
}): super(CarPartType.engine); | |
final int cylinders; | |
final int horsepower; | |
} | |
class Transmission extends CarPart { | |
const Transmission({ | |
required this.gears, | |
required this.isManual, | |
}): super(CarPartType.transmission); | |
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) { | |
switch (part.type) { | |
case CarPartType.engine: | |
part as Engine; | |
return 'A ${part.cylinders} cylinder engine ' | |
'which makes ${part.horsepower}hp.'; | |
default: | |
part as Transmission; | |
return 'A ${part.gears} speed ' | |
'${part.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