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?

+3


source to share


3 answers


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.

+5


source


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'

      

+2


source


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.

Constructors

Factories 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.

+1


source







All Articles