How to create a generic method in Dart?

jfp picture jfp · Feb 2, 2017 · Viewed 16.3k times · Source

I'm trying to use generic methods in Dart (1.22.0-dev.10.3). Here is a simple example:

abstract class VR<T> {
  VR();

  bool foo<T>(T value);
}

class VRInt extends VR<int> {
  VRInt();

  bool foo<int>(int n) => n > 0; // Thinks n is Object
}

class VRString extends VR<String> {
  VRString();

  bool foo<String>(String s) => s.length > 0; // Thinks s is Object
}

Both subclasses generate errors that say the argument to foo is an Object.

I'm sure this is just a syntactic error on my part, but I've searched the documentation and can't find an answer.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Feb 2, 2017

What you are doing could be done already before generic methods were introduced because you're just using the generic type parameter of the class. For this purpose just remove the type parameters on the methods to fix the problem.

Generic methods are to allow to pass a type that specializes a method no the call site

class MyClass {
  T myMethod<T>(T param) {
    prinz(param);
  }
}

and then use it like

new MyClass().myMethod<List<String>>(['a', 'b', 'c']);