Skip to content

Instantly share code, notes, and snippets.

@minikin
Last active November 20, 2020 10:52
Show Gist options
  • Save minikin/6cc34bc57cd8792e38908d06b39aa902 to your computer and use it in GitHub Desktop.
Save minikin/6cc34bc57cd8792e38908d06b39aa902 to your computer and use it in GitHub Desktop.
Types Promotion: Dart vs Swift
void main() {}
abstract class Shape {}
class Square implements Shape {
String? id;
}
class Circle implements Shape {
String? name;
}
class Rectangle implements Shape {
String? desc;
}
class Option {
String? id;
Shape? shape;
}
// It works. Dart can figure out types (subtypes).
void printShape(Shape shape) {
if (shape is Square) {
print(shape.id);
} else if (shape is Circle) {
print(shape.name);
} else if (shape is Rectangle) {
print(shape.desc);
}
}
// It doesn't work. Dart can't figure out a type.
void printOptions(Option option) {
if (option.shape is Square) {
if (option.shape != null) {
print(option.shape!.id);
}
} else if (option.shape is Circle) {
if (option.shape != null) {
print(option.shape!.name);
}
} else if (option is Rectangle) {
if (option.shape != null) {
print(option.shape!.desc);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment