Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dart types in action
class Car {
start() {}
}
class Mustang extends Car {
startGasEngine() {
print('Starting gas engine.');
}
openWindow() {}
}
class ModelS extends Car {
startElectricEngine() {
print('Starting electric engine.');
}
openWindow() {}
}
Car getCart(bool x) {
if (x) {
return new Mustang();
}
return new ModelS();
}
void addCar(List<Car> cars, Car car) {
cars.add(car);
}
void main(List<String> args) {
Car car = getCart(args[0] == 'mustang');
// dartanalyzer: The method 'startGasEngine' is not defined for the class 'Car'
// But it will run just fine.
car.openWindow();
// dartanalyzer: no issue
// Runtime will fail (`dart main.dart mustang`).
ModelS m = car;
m.startElectricEngine();
// dartanalyzer: no issue
// Runtime fail.
List<Mustang> cars = [];
addCar(cars, new ModelS());
cars[0].startGasEngine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment