Home > OS >  Why factory constructor can't be used in invoking superclass?
Why factory constructor can't be used in invoking superclass?

Time:10-11

Minimal reproducible code:

class Foo {
  Foo();
  factory Foo.named() => Foo();
}

class Bar extends Foo {
  Bar() : super.named(); // Error
} 

As there's no async-await thing in the factory constructor, and it instantly invokes the concrete constructor, so why isn't it allowed to use factory constructor like that?

Before null safety, null could be returned from a factory constructor but it is no longer a case. So, I think a factory constructor should now be allowed.

CodePudding user response:

factory function can return subclass, which means can call subclass's init function.

if subclass self can call super.factory function, then it become cycling.

CodePudding user response:

One of the main purposes of a factory constructor is to allow returning an existing instance. That's basically incompatible with a derived class constructor that must create a new object. (I suppose it doesn't necessarily have to be; you could imagine a design where two derived instances virtually inherit from a shared instance of a base class. However, that would be a lot of extra work for something of little benefit and that could be very confusing.)

Additionally, one of the other main purposes of a factory constructor is precisely to prevent a class from being subclassed by making all non-factory constructors private.

  •  Tags:  
  • dart
  • Related