Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generic method in Dart?

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.

like image 710
jfp Avatar asked Feb 02 '17 14:02

jfp


People also ask

How do you use generics in flutter?

Generics in Flutter The State class uses generics to make sure it deals only with the StatefulWidget it belongs to, using the syntax State<MyWidget> . A State instance is generic, written to work with any StatefulWidget, and in this case we're creating a state specifically for our MyWidget class.

How do I find my generic type Dart?

Could anybody clarify is there any option to get exact Type from generic parameter? You can do `Type myFunc<T>() => T`, which will return the `Type` object corresponding to the exact value of the actual type argument for the given invocation.


2 Answers

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']);
like image 122
Günter Zöchbauer Avatar answered Sep 25 '22 09:09

Günter Zöchbauer


Generic methods have type parameters that are not directly related to their class parameter types.

You can have a generic method on a class without generic:

class MyClass {
  T add<T>(T f()) => f();
}

You can also have a generic method on a class with generic:

class MyClass<A> {
  A aInstance;
  // here <T> is needed because unrelated to <A>
  T add<T>(T f(A a)) => f(aInstance);
}

In your case, you don't need the type parameter on the methods:

abstract class VR<T> {
  VR();

  bool foo(T value);
}

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

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

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

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

But there are no concept of generic method needed here.

like image 30
Alexandre Ardhuin Avatar answered Sep 22 '22 09:09

Alexandre Ardhuin