TypeVariance enum
Represents the variance annotations for generic type parameters in Dart.
Variance defines how generic type parameters behave with respect to subtyping:
- Covariant (out): Preserves subtyping direction
- Contravariant (in): Reverses subtyping direction
- Invariant: Neither covariant nor contravariant
{@template type_variance_features}
Values
covariant
: Marked withcovariant
keyword orout
in some languagescontravariant
: Marked within
keyword in some languagesinvariant
: Default variance with no keyword
Dart Usage
In Dart, variance is primarily expressed through:
covariant
keyword for parameters- Method parameter positions (contravariant)
- Default invariant behavior
Examples
// Covariant type parameter
class Box<out T> {
T get value => ...;
}
// Contravariant type parameter
class Consumer<in T> {
void accept(T value) {...}
}
// Invariant type parameter
class Holder<T> {
T value;
}
{@endtemplate}
Values
- covariant → const TypeVariance
-
Covariant type parameter (preserves subtyping).
A covariant type parameter preserves the subtyping relationship: If
A
is a subtype ofB
, thenContainer<A>
is a subtype ofContainer<B>
.Used for:
- Return types (output positions)
- Read-only fields
In Dart, marked with the
covariant
keyword. - contravariant → const TypeVariance
-
Contravariant type parameter (reverses subtyping).
A contravariant type parameter reverses the subtyping relationship: If
A
is a subtype ofB
, thenProcessor<B>
is a subtype ofProcessor<A>
.Used for:
- Parameter types (input positions)
- Write-only fields
In some languages marked with
in
keyword. - invariant → const TypeVariance
-
Invariant type parameter (no subtyping relationship).
An invariant type parameter allows no subtyping relationship between different instantiations of the generic type.
Used when:
- Type appears in both input and output positions
- No subtyping should be allowed between instantiations
This is the default variance in Dart.
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- index → int
-
A numeric identifier for the enumerated value.
no setterinherited
- name → String
-
Available on Enum, provided by the EnumName extension
The name of the enum value.no setter - runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Constants
-
values
→ const List<
TypeVariance> - A constant List of the values in this enum, in order of their declaration.