Last active
June 27, 2020 23:14
-
-
Save filiph/99f502497a3fd2d42543323945ffeaf3 to your computer and use it in GitHub Desktop.
Generics | The Self-Improving Developer
This file contains 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
// Generics for Beginners playground. | |
void main() { | |
var pants = Clothing(weight: 300); | |
var shirt = Clothing(weight: 200); | |
var satchel = Bag([pants, shirt]); | |
print(satchel.runtimeType); | |
var apple = Food(weight: 70, calories: 95); | |
var bread = Food(weight: 100, calories: 265); | |
var brownBag = Bag([apple, bread]); | |
print(brownBag.runtimeType); | |
// These work okay: | |
print(satchel.weight); | |
print(brownBag.weight); | |
// But we would like the next line to work. | |
// After all, we know that brownBag only | |
// contains food. | |
//print(brownBag.items.first.calories); | |
// TODO(you): Use generics to make the above work. | |
} | |
class Bag { | |
List<Item> items; | |
Bag(this.items); | |
/// Returns the weight of the whole bag, | |
/// including its contents. | |
int get weight { | |
// The bag itself is 300g. | |
int result = 300; | |
for (var item in items) { | |
result += item.weight; | |
} | |
return result; | |
} | |
} | |
abstract class Item { | |
/// Weight of the item in grams. | |
int get weight; | |
} | |
class Clothing extends Item { | |
int weight; | |
Clothing({this.weight}); | |
} | |
class Food extends Item { | |
int weight; | |
int calories; | |
Food({this.weight, this.calories}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment