dart-lang / dart-lang/language
Self type
- Dominant language
- TeX
- Stars
- 2.9k
- Forks
- 239
- Avg merge
- 2d 18h
- Merged PRs (30d)
- 14
Description
It'd be nice if a type could reliably refer to an implicit generic type argument representing the type of the instance.
Today you have to do something like:
```dart
abstract class Foo> { }
```
Now subclasses have to specify themselves as the type argument:
```dart
class BarFoo extends Foo { }
```
This leads to some weird errors when people aren't explicit about types (see https://github.com/dart-lang/sdk/issues/52204).
It also isn't completely safe. For example, I could copy and paste `BarFoo` to make `BazFoo` and make a mistake and not notice for a while:
```dart
class BazFoo extends Foo { } // no error, but the Self type is wrong
```
## Use case
I use this for classes that declare an API that I want to use in other generic contexts, e.g.:
```dart
@immutable
abstract class Status> {
const Status();
S copyWith();
S lerpTo(S other, double t);
bool matches(S other);
@override
operator ==(Object other) {
if (other.runtimeType != runtimeType)
return false;
return matches(other as S);
}
}
```
Now I have a type that I know I can clone, lerp, and compare, and so algorithms that are generic over that API can work on all the various subclasses of this type without needing to worry about the details.
(Obviously, true metaclasses would make this even more powerful, but I think this stands alone even without metaclasses.)
Contributor guide
Research direction
Start by reviewing the proposed Self-type examples and the related issue 52204 to understand the existing generic-type errors. Done would mean a language design that lets a type refer reliably to its instance type without requiring each subclass to repeat itself or silently use the wrong type argument.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- dart
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100