代码之家  ›  专栏  ›  技术社区  ›  Dimitris Andreou

子类的协方差返回类型

  •  0
  • Dimitris Andreou  · 技术社区  · 1 年前

    这里是飞镖初学者。

    abstract class Supertype {
      WithQuantity<Supertype> newQuantity(num quantity) =>
        WithQuantity(this, quantity)
    }
    
    class Subtype extends Supertype {
    }
    
    class WithQuantity<S extends Supertype> {
      final S thing;
      final num quantity;
      WithQuantity(this.thing, this.quantity);
    }
    
    void main() {
      WithQuantity<Subtype> quantityOfSubtype = Subtype().newQuantity(5);  
    }
    

    我想编译最后一行。

    在这个版本中当然没有,因为 newQuantity 退货 WithQuantity<Supertype> WithQuantity<Subtype> .

    我可以覆盖 newQuantity 方法来缩小返回类型,但我必须分别对每个子类执行此操作;似乎是重复的。

    在Java中,我本可以做这样的事情:

    class Supertype<S extends Supertype> {
      WithQuantity<S> newQuantity(...);
    }
    

    但是Dart不喜欢这种递归。

    我能告诉编译器我需要返回吗 WithQuantity<whateverMyRuntimeTypeIs> ?

    谢谢

    1 回复  |  直到 1 年前
        1
  •  2
  •   jamesdlin    1 年前

    你可以申报 Supertype 作为泛型,其类型参数是子类,然后显式强制转换 this 成为该子类类型:

    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> listOfSubtype = Subtype().newQuantity(5);
    }