简体   繁体   English

Dart:在抽象类中覆盖泛型函数时输入错误

[英]Dart: Type error when overrding generic function in abstract class

In Dart/ flutter I have the following classes:在 Dart/flutter 中,我有以下课程:

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. TypeA 和 TypeB 是用户定义的类型。 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>.但是,我收到错误消息:<The value of type B 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.我试图得到的是一个通用的 API 函数 foo(),其中输入和输出类型可以由实现的类灵活定义。

The problem is that TypeA and TypeB here are not user-defined types.问题是这里的TypeATypeB不是用户定义的类型。 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).Concrete.foo每次调用都需要传递类型参数,并且主体需要适用于任何类型参数(这就是“通用”的意思,它通常适用于任何类型)。

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.如果您尝试从Concrete.foo返回用户定义类型TypeA某些内容,则会出现错误,因为它没有类型变量TypeA ... 的类型,对于可以作为类型参数传递的任何类型。

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 .它使用实际的TypeATypeB参数化接口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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