How to implement generic class spezialization in Dart

Viewed 389

In Dart we can use generic classes [class]. We can also specialize those classes [class]. However at runtime the specialization is not used. (In C++ this is called template programming)

Example: The following code will result in the output

Hallo world How are you

class MyClass<T> {
  foo( print('Hallo world'); );
}

class MyClassInt implements MyClass<int> {
  @override
  foo( print('How are you'); );
}

main() {
  MyClass<int> a = Myclass<int>();
  MyClassInt b = MyClassInt();

  a.foo();
  b.foo();
}

How can the specialization (here type [int]) be done, that it is called at runtime, i.e.

main() {
  MyClass<int> a = Myclass<int>();

  a.foo();
}

should result in the outcome "How are you".

1 Answers

As mentioned by jamesdlin, Dart does not support specialization. But you can do something like this to make the illusion:

class MyClass<T> {
  factory MyClass() {
    if (T == int) {
      return MyClassInt() as MyClass<T>;
    } else {
      return MyClass._();
    }
  }

  // Hidden real constructor for MyClass
  MyClass._();

  void foo() {
    print('Hallo world');
  }
}

class MyClassInt implements MyClass<int> {
  @override
  void foo() {
    print('How are you');
  }
}

void main() {
  final a = MyClass<int>();
  final b = MyClassInt();
  final c = MyClass<String>();

  a.foo(); // How are you
  b.foo(); // How are you
  c.foo(); // Hallo world
}
Related