Why is an abstract instance of a class not a runtime error in dart?
In many languages, if you try to instantiate an abstract class, you get a compile-time error. However, in Dart you get a compile-time warning and a runtime exception AbstractClassInstantiationError
.
Why? Can anyone provide an example where it is reasonable to compile code like this?
source to share
Dart tries to allow you to run your program while it is developing. This is why many things that are compile-time errors in other languages are compile-time warnings and run-time errors in Dart. This includes "x is Foo" where Foo does not exist, type-annotation with non-existent types, and calling constructors of partial (abstract) classes.
In short: because it is not a problem that prevents the program from compiling (as opposed to a syntax error, which can mean the rest of the file is being misinterpreted), there is no reason to stop you from running the code. Only if you push the branch that actually depends on the problem will your program stop.
source to share
It looks like the answer is a factory constructor in an abstract class:
abstract class Foo { factory Foo() { // make Foo appear to be instantiable return new Bar(); } some(); // some abstract method Foo.name() {} just a named constructor } class Bar extends Foo { Bar():super.name(); // call named super constructor some() {} // implement abstract method } main() { print(new Foo()); // "instantiate" abstract Foo }
Output:
Instance of 'Bar'
source to share
Asking "where is it reasonable to compile such code?" in Dart is not very significant because Dart is an interpreted language - there is no compilation stage. Dart editors will issue warnings if they think you are making a type error when they parse your code on the fly.
ConstructorsFactories can be used to provide a concrete implementation of a default abstract class, as you did in your example. It is used quite widely in Dart. For example, if you create a new object Map
, you actually get the object LinkedHashMap
- see this question and answer .
In your example, you are not instantiating Foo
('new Foo' does not appear anywhere), you are creating `Bar '. This is because when a factory constructor is created, a new instance of its class is not automatically created.
source to share