dart-lang / dart-lang/language
Static nested classes
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
Allow declaring a class in the body of another class.
```dart
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 `StatefulWidget`s and their respective `State`s)
* Creating arbitrary namespaces like `export _ as _` but without a library declaration file
* Encapsulating many related methods under a namespace
Contributor guide
Assessment
This issue has not been assessed yet.