简体   繁体   中英

Dart abstract class with generic factory

I have an abstract class with a generic type. I want this class to define a factory so if an implementing class doesn't have this defined, it gives a warning. However I can't figure out how to do this when using a generic type. The abstract class just keep giving me errors.

Here's my class with some examples of non-working solutions:

abstract class Bar<T> {

  // Error: The class 'Bar' doesn't have a default constructor
  factory Bar.someFn(Map<String, dynamic> myMap) => Bar<T>(myMap);

  // Error 1: The name of a factory constructor must be the same as the name of the immediately enclosing class
  // Error 2: 'T' isn't a function.
  // Error 3: Try correcting the name to match an existing function, or define a method or function named 'T'
  factory T.someFn(Map<String, dynamic> myMap) => T(myMap);
}

Having a correct abstract class would yield the following:

// BAD!
class Foo implements Bar<Foo> {
  
  // Missing implementation of someFn
}

// OK!
class Foo implements Bar<Foo> {

  @override
  factory Foo.someFn(Map<String, dynamic> myMap) => Foo(x: myMap['x'], y: myMap['y']);
}

Is there a way to achieve what I want?

No.

Constructors are not inherited, they are not part of any interface, so nothing you write in the superclass will affect the constructors of the subclass.

Each class can define its own constructors. The only thing you can do is to add a generative constructor to the superclass, then subclasses which extend the superclass (not just implement its interface), will have to call that superclass constructor as their super-constructor invocation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM