language icon indicating copy to clipboard operation
language copied to clipboard

Static nested classes

Open dz4k opened this issue 5 years ago • 32 comments

Allow declaring a class in the body of another class.

class Person {
  class Occupation {
    String jobTitle;
    Occupation(this.jobTitle);
    String named(String name) =>
      moniker(Person(name, this));
  } 
  String name;
  Occupation occupation;
  Person(this.name, this.occupation);
  static String moniker(Person p) =>
      '${p.name} The ${p.occupation.jobTitle}';
}
Person p = Person("Rosie", Person.Occupation("Riveter"));

I'd expect that Occupation is not an instance variable of Person, if that would even be a sensible notion in Dart, instead the outer class acts as a namespace containing the inner class. The inner class cannot be accessed from a Person instance. The inner class cannot capture instance variables from the outer class. It can howewer access static methods and fields.

Nested classes could be used for:

  • Indicating a relationship between classes / encapsulating classes which only serve to complement another (e.g. Flutter StatefulWidgets and their respective States)
  • Creating arbitrary namespaces like export _ as _ but without a library declaration file
  • Encapsulating many related methods under a namespace

dz4k avatar Apr 29 '19 19:04 dz4k