Last active
January 21, 2020 18:25
-
-
Save dpossas/6f5a251ee98c51bfbe79dddc679c16f6 to your computer and use it in GitHub Desktop.
Dart - Override Operators
This file contains hidden or 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
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