A function or data structure is parameterized by types and can operate uniformly over their instantiations.
// Target: computer-science.bigb
An object method with its own type parameters, instantiated or inferred at each call. In Scala,
def identity[T](x: T): T = x is a generic method. A method def accept(x: T) inside class Box[T] instead uses a class type parameter fixed by the receiver's type argument; it is not itself a generic method with a separately chosen T on every call. This distinction matters in method overloading.A type scheme describing a family of instances through type variables. In Hindley-Milner type inference, a principal type describes the most general valid instance pattern; concrete types arise by consistently substituting for the quantified variables. Reusing one variable constrains the corresponding positions to the same type, whereas distinct variables can vary independently.
A type parameter is a named variable ranging over admissible types in a generic definition. Instantiation substitutes a particular type argument, allowing one declaration to retain type information across uses. An upper type bound restricts the admissible arguments; a variance annotation instead describes how instantiated types participate in subtyping.
A type substituted for a type parameter when a generic declaration is instantiated. A type argument must satisfy the declaration's upper and lower bounds. It is distinct from an ordinary run-time argument supplied to a function call.
A parameter position for which implies . In Scala, it is annotated
-. A consumer capable of accepting every broad-type value can safely serve a context that supplies only narrower values. Returning a value of that parameter type would generally break this guarantee.A parameter position for which implies . In Scala, it is annotated
+. An immutable producer can return narrower values where broader values are expected. A method consuming that parameter directly would generally make covariance unsafe, since a widened reference could then receive unsupported inputs.Suppose a mutable collection of narrow-type values could be viewed as a mutable collection of a wider type. Inserting a wider-only value through that alias would make a subsequent narrow-type read invalid. For example, hypothetical covariance would let one insert a string through an
Any-typed alias of an integer multiset. Generic type invariance prevents that substitution; making a parameter covariant does not authorize an unsound consuming method.How subtyping between parameter types affects subtyping between instances of a parameterized type. A covariant type parameter preserves the direction, a contravariant type parameter reverses it, and generic type invariance permits neither conversion solely from the parameter relationship. Safe variance depends on how a type is consumed, produced and stored.
Articles by others on the same topic
There are currently no matching articles.