Skip to content

Wildcard type bounds #54108

@lukehutch

Description

@lukehutch

Java has wildcard type bounds, e.g. ? extends SomeClass. Dart does not.

This can cause runtime type errors in Dart for people like me who have a hard time reasoning through covariance...

For example

class Table {}

class TableSubclass extends Table {}

class Inner<T extends Table> {
  final bool Function(T) test;
  Inner(this.test);
}

class Outer {
  final Inner<Table> inner;
  Outer(this.inner);
}

void main() {
  final inner = Inner<TableSubclass>((t) => true);
  print(inner.test(TableSubclass()));
  final outer = Outer(inner);
  print(outer.inner.test(TableSubclass()));
}

This prints

true
Uncaught Error: TypeError: Closure 'main_closure': type '(TableSubclass) => bool' is not a subtype of type '(Table) => bool'

Whereas if you change Outer to

class Outer<T extends Table> {
  final Inner<T> inner;
  Outer(this.inner);
}

the output is

true
true

This seems to indicate that you should be able to do

class Outer {
  final Inner<? extends Table> inner;
  Outer(this.inner);
}

but wildcard type bounds are not supported in Dart.

This becomes more important when inner is not a single value, but a list: List<Inner<Table>> inners -- since with a list of arbitrary length, you can't just impose a fixed number type bounds on the surrounding class. You should be able to do List<Inner<? extends Table>> inners in this case.

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