Notice: This question is obsolete; the
interfacedeclaration syntax has been removed from Dart:
Proposal to eliminate interface declarations from Dart
“In Dart, every class engenders an implicit interface. Now that this feature is implemented, it is possible to actually eliminate interface declarations from the language. Interface declarations are replaced by purely abstract classes.”
As far as I’ve been able to tell, it’s impossible to instantiate an interface in Dart. If I simply try to construct a new MyInterface(), with or without a constructor defined, I get a run-time error (try it):
NoSuchMethodException - receiver: '' function name: 'MyInterface$$Factory' arguments: []]
interface MyInterface {}
interface MyInterface {
MyInterface();
}
If I try to use a factory constructor instead, returning an instance of an implementation, I get a compile-time error (try it):
SyntaxError: factory members are not allowed in interfaces
class MyImplementation implements MyInterface {
MyImplementation();
}
interface MyInterface {
factory MyInterface() { return new MyImplementation(); }
}
However, this seems at-odds with the reality that List<E>1 in Dart’s core library is an interface2, yet it has several constructors and can be instantiated. For example, this works fine (try it):
main() {
var list = new List();
list.add(5);
print(list.last());
}
Why can List and many other built-in interfaces be instantiated? Is there some method I missed or are they just receiving special treatment as built-in types?
1 Dart: Libraries: corelib: interface List<E>
2 “Much of the Dart Core Library is defined in terms of interfaces.”3
3 Dart: Tutorial: Interfaces
The syntax for defining an interface is:
Notice that the
factorySpecificationmust come before the body of the interface rather than inside it.So this is how you write it:
Or if you want to go for the full generic definition:
Edit: For a more complete example, you can read the source code for the
interface List<E>at https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/corelib/src/list.dart and the associatedclass ListFactory<T>source is at https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/runtime/lib/array.dart