dart-lang / language

Design of the Dart language
Other
2.65k stars 202 forks source link

Support Abstract Type Members #3628

Open anqit opened 6 months ago

anqit commented 6 months ago

Scala, for one, offers the concept of abstract type members, and it would be great to see this supported in Dart. Abstract type members provide both ergonomic convenience (by not having to repeatedly specify type parameters) as well as a way to specify valid mappings or combinations of types and preventing invalid combinations. For example, when modeling generic entities with arbitrary id types, currently we need to do something like this:

abstract class Entity<Id> { ... }
abstract class EntityRepo<Id, E extends Entity<Id>> {
    E getById(Id id) ...
}

With the capability of defining a type member though, this could be a bit simpler, as with the following pseudo-syntax:

abstract class Entity {
    type Id
}
abstract class EntityRepo<E extends Entity> {
    E getById(E.Id id) ...
}

Not only is this less verbose, it can prevent creating invalid combinations of, in this case, entity and id types.

lrhn commented 6 months ago

Another solution for this is type patterns. If you could write:

abstract class EntityRepo<E extends Entity<var Id>> {
    E getById(Id id) ...
}

And automatically get the type parameter type of the actual Entity subtype bound to E as a type variable, then we don't need another easy to parameterize Entity with a type.