@@ -78,6 +78,22 @@ object Option {
7878}
7979```
8080
81+ Enumerations and ADTs have been presented as two different
82+ concepts. But since they share the same syntactic construct, they can
83+ be seen simply as two ends of a spectrum and it is perfectly possible
84+ to construct hybrids. For instance, the code below gives an
85+ implementation of ` Color ` either with three enum values or with a
86+ parameterized case that takes an RGB value.
87+
88+ ``` scala
89+ enum Color (val rgb : Int ) {
90+ case Red extends Color (0xFF0000 )
91+ case Green extends Color (0x00FF00 )
92+ case Blue extends Color (0x0000FF )
93+ case Mix (mix : Int ) extends Color (mix)
94+ }
95+ ```
96+
8197### Parameter Variance of Enums
8298
8399By default, parameterized cases of enums with type parameters will copy the type parameters of their parent, along
@@ -112,25 +128,20 @@ and can remedy the error by the following change to `Refl`:
112128``` diff
113129enum View[-T]:
114130- case Refl(f: T => T)
115- + case Refl[U ](f: U => U ) extends View[U ]
131+ + case Refl[R ](f: R => R ) extends View[R ]
116132```
117- Above, type ` U ` is chosen as the parameter for ` Refl ` to highlight that it has a different meaning to
133+ Above, type ` R ` is chosen as the parameter for ` Refl ` to highlight that it has a different meaning to
118134type ` T ` in ` View ` , but any name will do.
119135
120- Enumerations and ADTs have been presented as two different
121- concepts. But since they share the same syntactic construct, they can
122- be seen simply as two ends of a spectrum and it is perfectly possible
123- to construct hybrids. For instance, the code below gives an
124- implementation of ` Color ` either with three enum values or with a
125- parameterized case that takes an RGB value.
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 ` :
126138
127139``` scala
128- enum Color (val rgb : Int ) {
129- case Red extends Color (0xFF0000 )
130- case Green extends Color (0x00FF00 )
131- case Blue extends Color (0x0000FF )
132- case Mix (mix : Int ) extends Color (mix)
133- }
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)
134145```
135146
136147### Syntax of Enums
0 commit comments