Skip to content

Instantly share code, notes, and snippets.

@dpossas
Last active January 21, 2020 18:25
Show Gist options
  • Save dpossas/6f5a251ee98c51bfbe79dddc679c16f6 to your computer and use it in GitHub Desktop.
Save dpossas/6f5a251ee98c51bfbe79dddc679c16f6 to your computer and use it in GitHub Desktop.
Dart - Override Operators
void main() {
Bag bag = Bag(items: []);
print('Total: ${bag.total}');
Product p1 = Product(name: 'Pen', price: 1.15);
print('Total: ${bag+p1}');
Product p2 = Product(name: 'Pencil', price: 2);
print('Total: ${bag+p2}');
}
class Bag {
List<Product> items;
double total;
Bag({this.items, this.total = 0});
double operator +(Product product) {
items.add(product);
total += product.price;
return total;
}
}
class Product {
String name;
double price;
Product({this.name, this.price});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment