@@ -94,6 +94,56 @@ enum Color(val rgb: Int) {
9494}
9595```
9696
97+ ### Parameter Variance of Enums
98+
99+ By default, parameterized cases of enums with type parameters will copy the type parameters of their parent, along
100+ with any variance notations. As usual, it is important to use type parameters carefully when they are variant, as shown
101+ below:
102+
103+ The following ` View ` enum has a contravariant type parameter ` T ` and a single case ` Refl ` , representing a function
104+ mapping a type ` T ` to itself:
105+ ``` scala
106+ enum View [- T ]:
107+ case Refl (f : T => T )
108+ ```
109+ The definition of ` Refl ` is incorrect, as it uses contravariant type ` T ` in the covariant result position of a
110+ function type, leading to the following error:
111+ ``` scala
112+ -- Error : View .scala: 2 : 12 --------
113+ 2 | case Refl (f : T => T )
114+ | ^^^^^^^^^
115+ | contravariant type T occurs in covariant position in type T => T of value f
116+ | enum case Refl requires explicit declaration of type T to resolve this issue.
117+ ```
118+ Because ` Refl ` does not declare explicit parameters, it looks to the compiler like the following:
119+ ``` scala
120+ enum View [- T ]:
121+ case Refl [/* synthetic*/ - T1 ](f : T1 => T1 ) extends View [T1 ]
122+ ```
123+
124+ The compiler has inferred for ` Refl ` the contravariant type parameter ` T1 ` , following ` T ` in ` View ` .
125+ We can now clearly see that ` Refl ` needs to declare its own non-variant type parameter to correctly type ` f ` ,
126+ and can remedy the error by the following change to ` Refl ` :
127+
128+ ``` diff
129+ enum View[-T]:
130+ - case Refl(f: T => T)
131+ + case Refl[R](f: R => R) extends View[R]
132+ ```
133+ Above, type ` R ` is chosen as the parameter for ` Refl ` to highlight that it has a different meaning to
134+ type ` T ` in ` View ` , but any name will do.
135+
136+ After some further changes, a more complete implementation of ` View ` can be given as follows and be used
137+ as the function type ` T => U ` :
138+
139+ ``` scala
140+ enum View [- T , + U ] extends (T => U ):
141+ case Refl [R ](f : R => R ) extends View [R , R ]
142+
143+ final def apply (t : T ): U = this match
144+ case refl : Refl [r] => refl.f(t)
145+ ```
146+
97147### Syntax of Enums
98148
99149Changes to the syntax fall in two categories: enum definitions and cases inside enums.
0 commit comments