Covariance and contravariance (computer science): Difference between revisions

Content deleted Content added
RnTkm (talk | contribs)
Undid revision 1054485302 by RnTkm (talk). withdraw
m Data: Cleanup and typo fixing, typo(s) fixed: similarly- → similarly
Line 379:
First, class members that have a variant type must be immutable. Here, <syntaxhighlight lang="scala" inline>head</syntaxhighlight> has the type <syntaxhighlight lang="scala" inline>A</syntaxhighlight>, which was declared covariant (<syntaxhighlight lang="scala" inline>+</syntaxhighlight>), and indeed <syntaxhighlight lang="scala" inline>head</syntaxhighlight> was declared as a method (<syntaxhighlight lang="scala" inline>def</syntaxhighlight>). Trying to declare it as a mutable field (<syntaxhighlight lang="scala" inline>var</syntaxhighlight>) would be rejected as type error.
 
Second, even if a data structure is immutable, it will often have methods where the parameter type occurs contravariantly. For example, consider the method <syntaxhighlight lang="scala" inline>::</syntaxhighlight> which adds an element to the front of a list. (The implementation works by creating a new object of the similarly- named ''class'' <syntaxhighlight lang="scala" inline>::</syntaxhighlight>, the class of nonempty lists.) The most obvious type to give it would be
 
<syntaxhighlight lang="scala">