dart-lang / dart-lang/language

Safe typing involving variance

Open
#213 8 comments 59 reactions 0 assignees View on GitHub
request variance
Dominant language
TeX
Stars
2.9k
Forks
239
Avg merge
2d 18h
Merged PRs (30d)
14

Description

In Dart, a parameterized class type is covariant in every type parameter; for example, `List` is a subtype of `List` because `int` is a subtype of `num` (so the list type and its type argument "co-vary").

This is sound for all covariant occurrences of such type parameters in the class body (for instance, the getter `first` of a list has return type `E`, which is sound). It is also sound for contravariant occurrences when a sufficiently exact receiver type is known (e.g., for a literal like `[].add(4.2)`, or for a generative constructor `SomeClass.foo(4.2)`).

However, in general, every member access where a covariant type parameter occurs in a contravariant position may cause a dynamic type error, because the actual type annotation at run time—say, the type of a parameter of a method—is a subtype of the one which is known at compile-time.

For example: Assume that a variable `xs` has declared type `List`, and consider the invocation `xs.add(4.2)`. This invocation will fail if the value of `xs` is a `List`, but it will succeed with a `List` and with a `List`. Still, the static type of `xs` allows them all.

This issue is a request for improvements in the amount of control that developers have over this kind of dynamic checks. In particular, it should be possible to establish a guarantee at compile time that such a dynamic type error cannot occur.

Contributor guide

Open the contributing guide

Research direction

Start with the issue's examples involving List, List, and contravariant member access. The request is for compile-time control or guarantees around dynamic type errors, but no files, tests, or implementation entry points are identified. Done would require a defined language-design approach and corresponding specification or implementation changes.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.