简体   繁体   中英

Dart: Type error when overrding generic function in abstract class

In Dart/ flutter I have the following classes:

abstract class Base {
   V foo<V, T>(T arg);
}

class Concrete implements Base {
   @override
   TypeA foo<TypeA, TypeB>(TypeB arg) {
       //... do something and return TypeA variable x
       return x;
   }
}

TypeA and TypeB are user defined types. However, I get the error message: <The value of type TypeB can't be returned from method 'foo' because it has a return type of TypeB>. Wired! Could you help me to understand what is going on here. What I try to get to is a general API function foo() where the input and output type can be defined flexibly by implemented classes.

The problem is that TypeA and TypeB here are not user-defined types. They are type variables which happen to have the same name as a user defined type. Each call to Concrete.foo would need to pass type arguments, and the body needs to work for any type arguments (that's what being "generic" means, it works on generally for any type).

If you try to return something of the user-defined type TypeA from Concrete.foo , you get an error because it does not have the type of the type variable TypeA ... for any type that can be passed as a type argument.

My guess is that what you want is a generic class:

abstract class Base<V, T> {
   V foo(T arg);
}

class Concrete implements Base<TypeA, TypeB> {
   @override
   TypeA foo(TypeB arg) {
       //... do something and return TypeA variable x
       return x;
   }
}

which parameterizes the interface with the actual TypeA and TypeB .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM