How do I guarantee a certain named constructor in Dart?

安稳与你 提交于 2021-01-03 06:38:04

问题


Let us say I have the concrete classes Cat, Dog, and Parrot, and the following interface:

class HasGuid {
  HasGuid.fromId(String id);
}

My goal is to guarantee that Cat, Dog, and Parrot all have a fromId named constructor. So, I can make calls like:

Cat.fromId("Whiskers") =returns> [A Future<Cat> object with id "Whiskers"]
Dog.fromId("Fido")     =returns> [A Future<Dog> object with id "Fido"]
Parrot.fromId("Polly") =returns> [A Future<Parrot> object with id "Poly"]

fromId is making a call across the network, for this reason I return it as a Future. I basically want a contract that states that any class that mixes/extends/implements/whatever the HasGuid class will have a named constructor of fromId. Where fromId on class T will take an identity string and will return a Future<T>.


回答1:


There can be no assurance on constructor.

Interface(implements) assurance on instance methods. Super class(extends) or Mixins(with) also assurance on instance methods, not constructor.

Constructor return it's own type, not a Future.

So they should all have a static method or class, but no guarantee.




回答2:


The short answer is that you cannot force a subclass to implement a specific named constructor ... all you can do is force the subclass to make sure the named constructor is called by the subclass.

Take for example the following ...

class Animal {
  String name;

  Animal.fromName(this.name);
}

class Dog extends Animal {

  Dog.withName(String name) : super.fromName(name);
}

Note the following ...

  1. Animal has no zero argument constructor.
  2. If you don't call the super.fromName() constructor from Dog you will get a compile error
The superclass 'Animal' doesn't have a zero argument constructor.
  1. Although Dog must call the fromName() constructor ... it doesn't have to call its named constructor the same. In this case notice it is called withName().


来源:https://stackoverflow.com/questions/16129007/how-do-i-guarantee-a-certain-named-constructor-in-dart

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