Menu
Coddy logo textTech

Recap - Generic Storage

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 69 of 110.

challenge icon

Challenge

Easy

Let's build a generic storage system that combines everything you've learned about collections and generics! You'll create a Storage<T> class that can store items of any type, retrieve them, and be iterated over using a for-in loop.

You'll organize your code into two files:

  • storage.dart: Create your generic storage system with two classes:
    • A StorageIterator<T> class that implements Iterator<T> to enable iteration over stored items
    • A Storage<T> class that extends Iterable<T> with the following capabilities:
      • A private list to hold items internally
      • An add(T item) method to store a new item
      • A getAt(int index) method that returns the item at the given index
      • A count getter that returns the number of stored items
      • An iterator getter that returns a StorageIterator for the stored items
  • main.dart: Import your storage file and demonstrate the generic storage with different types:
    • Create a Storage<String> and add three city names: 'Paris', 'Tokyo', 'Sydney'
    • Print the count of items
    • Print the item at index 1
    • Use a for-in loop to print each city on its own line
    • Print an empty line
    • Create a Storage<int> and add four numbers: 100, 200, 300, 400
    • Use the where method to filter values greater than 150, then print the resulting list

Your storage system should work seamlessly with any type while maintaining full type safety. Because it extends Iterable, it automatically gains access to powerful methods like where, map, and fold!

Expected output:

Count: 3
Item at 1: Tokyo
Paris
Tokyo
Sydney

[200, 300, 400]

Try it yourself

import 'storage.dart';

void main() {
  // TODO: Create a Storage<String> for cities
  // Add three cities: 'Paris', 'Tokyo', 'Sydney'

  // TODO: Print the count of items (format: "Count: X")

  // TODO: Print the item at index 1 (format: "Item at 1: X")

  // TODO: Use a for-in loop to print each city on its own line

  // TODO: Print an empty line
  print('');

  // TODO: Create a Storage<int> for numbers
  // Add four numbers: 100, 200, 300, 400

  // TODO: Use where method to filter values greater than 150
  // Then print the resulting list using toList()
}

All lessons in Object Oriented Programming