Skip to content

Instantly share code, notes, and snippets.

Last active December 21, 2022 00:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Pattern matching 3
abstract class CarPart {}
class Engine implements CarPart {
const Engine({
required this.cylinders,
required this.horsepower,
final int cylinders;
final int horsepower;
class Transmission implements CarPart {
const Transmission({
required this.gears,
required this.isManual,
final int gears;
final bool isManual;
class Car {
const Car(
this.model, {
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.',
String _getDescriptionForCarPart(CarPart part) {
if (part is Engine) {
return 'A ${part.cylinders} cylinder engine '
'which makes ${part.horsepower}hp.';
} else {
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),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment