Calling method on generic type Dart

你离开我真会死。 提交于 2020-05-15 08:31:30

问题


I am trying to get a way to call method on a generic type. But can't find it.

In swift I can write like:

protocol SomeGeneric {
    static func createOne() -> Self
    func doSomething()

}

class Foo: SomeGeneric {
    required init() {

    }
    static func createOne() -> Self {
        return self.init()
    }

    func doSomething() {
        print("Hey this is fooooo")
    }
}

class Bar: SomeGeneric {
    required init() {

    }

    static func createOne() -> Self {
        return self.init()
    }

    func doSomething() {
        print("Hey this is barrrrrrr")
    }
}

func create<T: SomeGeneric>() -> T {
    return T.createOne()
}

let foo: Foo = create()
let bar: Bar = create()

foo.doSomething() //prints  Hey this is fooooo
bar.doSomething() //prints  Hey this is barrrrrrr

In Dart I tried:

abstract class SomeGeneric {
  SomeGeneric createOne();
  void doSomething();
}

class Foo extends SomeGeneric {
  @override
  SomeGeneric createOne() {
    return Foo();
  }

  @override
  void doSomething() {
    print("Hey this is fooooo");
  }
}

class Bar extends SomeGeneric {
  @override
  SomeGeneric createOne() {
    return Bar();
  }

  @override
  void doSomething() {
    print("Hey this is barrrrr");
  }
}

T create<T extends SomeGeneric>() {
  return T.createOne();//error: The method 'createOne' isn't defined for the class 'Type'.
}

The code gives error The method 'createOne' isn't defined for the class 'Type' How to fix this?. If this is possible, it would save lot of time and tons of lines of code.


回答1:


It is not possible. In Dart you cannot call static methods through a type-variable because static methods must be resolved at compile-time and type-variables do not have a value until run-time. Dart interfaces are not Swift protocols, they can only specify instance methods.

If you want to parameterize a class with the ability to create a new object of a type, you need to pass a function doing so:

void floo<T>(T create(), ...) { 
   ...
   T t = create();
   ...
}

You cannot rely on the type variable alone for that.



来源:https://stackoverflow.com/questions/55901883/calling-method-on-generic-type-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!