Description
Dart has no abstract variable declaration. If you need to add an instance field to an interface, without introducing a backing cell in the class, you have to write both a getter and a setter.
In the case of classes that are only used as interfaces, you currently can write a field declaration:
abstract class MyInterface {
int age;
String name;
}
As long as everybody implements this interface instead of extending it, it doesn't matter that the class technically isn't abstract and allocates memory for the two members in every instance. After all, there will be no instances.
When we move to Null Safety (nee NNBD), that interface will no longer work.
Both fields will become a non-nullable, and therefore they need to be initialized by the constructor.
The interface has no constructor, and currently doesn't need one. That means that it gets the default constructor which doesn't initialize any fields (could be fixed by #469, though).
So, to avoid the issue, the interface owner can either add a factory constructor like
factory MyInterface._() => throw UnsupportedError("Dammit Jim, I'm an interface, not a class!");
or change the declarations to getters and setters.
Either choice introduces otherwise unnecessary noise.
It would be nice if there was a way to declare a field abstract without too much extra syntax.
Activity
lrhn commentedon Jan 27, 2020
Added proposal for solution: https://github.com/dart-lang/language/blob/master/working/00798%20-%20Abstract-External%20Variables/proposal.md
rrousselGit commentedon Jan 27, 2020
Nice!
Another use-case for that is that it works as syntax sugar for abstract properties on mixins:
lrhn commentedon Jan 27, 2020
True, mixins is another use case where you might want to declare abstract fields. Good one.
lrhn commentedon Jan 27, 2020
Hmm, appears we already had #44, I'll just defer to that instead.