![](/img/trans.png)
[英]Type error when when trying to override a generic function in a concrete implementation of an abstract class
[英]Dart: Type error when overrding generic function in abstract class
在 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 和 TypeB 是用戶定義的類型。 但是,我收到錯誤消息:<The value of type B can't be returned from method 'foo' because it has a return type of TypeB>。 有線! 你能幫我理解這里發生了什么嗎? 我試圖得到的是一個通用的 API 函數 foo(),其中輸入和輸出類型可以由實現的類靈活定義。
問題是這里的TypeA
和TypeB
不是用戶定義的類型。 它們是恰好與用戶定義的類型同名的類型變量。 對Concrete.foo
每次調用都需要傳遞類型參數,並且主體需要適用於任何類型參數(這就是“通用”的意思,它通常適用於任何類型)。
如果您嘗試從Concrete.foo
返回用戶定義類型TypeA
某些內容,則會出現錯誤,因為它沒有類型變量TypeA
... 的類型,對於可以作為類型參數傳遞的任何類型。
我的猜測是你想要的是一個泛型類:
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;
}
}
它使用實際的TypeA
和TypeB
參數化接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.