Skip to content

Allow abstract variable declarations in interfaces. #798

Closed
@lrhn

Description

@lrhn

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

added
requestRequests to resolve a particular developer problem
on Jan 27, 2020
rrousselGit

rrousselGit commented on Jan 27, 2020

@rrousselGit

Nice!
Another use-case for that is that it works as syntax sugar for abstract properties on mixins:

mixin Example {
  int get a;
  set a(int value);

  abstract String b;
}

class Concrete with Example {
  @override
  int a;
  @override
  String b;
}
lrhn

lrhn commented on Jan 27, 2020

@lrhn
MemberAuthor

True, mixins is another use case where you might want to declare abstract fields. Good one.

lrhn

lrhn commented on Jan 27, 2020

@lrhn
MemberAuthor

Hmm, appears we already had #44, I'll just defer to that instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problemstate-duplicateThis issue or pull request already exists

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @lrhn@rrousselGit

        Issue actions

          Allow abstract variable declarations in interfaces. · Issue #798 · dart-lang/language