Skip to content

Specialize interfaces for specific generic types on a class #276

Closed
@natebosch

Description

@natebosch

Solution for #275

Add a way to put conditions on the existence of a constructor or method depending on the specific generic type of a class. I think this would apply to the static type at the callsite.

This would let us statically prevent certain calls that would otherwise have to throw at runtime.

Separately, in the discussion for static extension methods we learned that it may be possible to write an extension that is specialized based on the generic type. This gives us a capability with extension methods that isn't possible with instance methods. Adding instance methods conditional on the specific generic type would bring this same power without needing to separate out the implementation to a extension.

Straw man:

class List<E> {
  List.filled(int size, E fill);
  List([int size]) if E extends Object;

  num sum() if E extends num;
}

void main() {
  var list1 = List<int>.filled(5, 1);
  var list2 = List<int>(1); // static error. "The class 'List<int>' does not have a default constructor."
  print(list1.sum());
  var list3 = ["Hello"];
  print(list3.sum()); // static error. "The method 'sum' isn't defined for the class 'List<String>'."
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions