You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart子类协变返回类型实现:使newQuantity返回子类泛型实例

让Dart父类方法返回对应子类泛型类型的解决方案

你可以通过递归泛型实现需求,Dart其实支持这种写法,只是需要正确声明泛型约束。以下是修改后的代码:

abstract class Supertype<S extends Supertype<S>> {
  WithQuantity<S> newQuantity(num quantity) =>
    WithQuantity(this as S, quantity);
}

class Subtype extends Supertype<Subtype> {
}

class WithQuantity<S extends Supertype<S>> {
  final S thing;
  final num quantity;
  WithQuantity(this.thing, this.quantity);
}

void main() {
  WithQuantity<Subtype> quantityOfSubtype = Subtype().newQuantity(5);  // 编译通过
}

关键说明:

  • 给Supertype添加递归泛型参数S extends Supertype<S>,要求泛型参数必须是自身的子类(即子类继承时需传入自身作为泛型参数,比如Subtype extends Supertype<Subtype>)。
  • 将newQuantity的返回类型改为WithQuantity<S>,这样子类调用该方法时,返回值会自动适配子类的泛型类型,无需重写方法。
  • 方法内的this as S是安全的类型转换:由于递归泛型的约束,this的实际运行时类型必然是S,编译器只是无法自动推断这一点,所以需要显式转换。

这种写法避免了每个子类重复重写newQuantity的冗余操作,和你熟悉的Java递归泛型思路一致。

内容的提问来源于stack exchange,提问作者Dimitris Andreou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 14:43:12