@@ -77,6 +77,7 @@ enum Planet(mass: Double, radius: Double):
77
77
end Planet
78
78
```
79
79
80
+ ### User-defined companion object of enums
80
81
It is also possible to define an explicit companion object for an enum:
81
82
82
83
``` scala
@@ -89,13 +90,15 @@ object Planet:
89
90
end Planet
90
91
```
91
92
92
- As explained [ later] ( ./desugarEnums.md ) , enum cases are expanded in the companion object of the enum.
93
- Even though the enum cases are written within the lexical scope of the enum template, they may not
94
- reference members of the enum class. Like secondary constructors, although written inside the template,
95
- they are scoped outside it.
93
+ ### Restrictions on Enum Cases
96
94
97
- Similarly, they may not directly reference members of the companion object in which they expand.
98
- They are like default class arguments, which are also expanded in the class's companion. For example:
95
+ Enum case declarations are similar to secondary constructors:
96
+ they are scoped outside of the enum template, despite being declared within it.
97
+ This means that enum case declarations cannot access inner members of the
98
+ enum class.
99
+
100
+ Similarly, enum case declarations may not directly reference members of the enum's companion object,
101
+ even if they are imported (directly, or by renaming). For example:
99
102
100
103
``` scala
101
104
import Planet .*
@@ -110,9 +113,9 @@ object Planet:
110
113
private final val (EarthMass @ _, EarthRadius @ _) = (5.976e+24 , 6.37814e6 )
111
114
end Planet
112
115
```
113
- The fields for Mercury are not visible, and the fields for Venus may not be referenced directly.
114
- Since the direct reference after expansion shadows any import clause, the import statement does not make the fields available.
115
- Direct references using a renaming import are also disallowed .
116
+ The fields referenced by ` Mercury ` are not visible, and the fields referenced by ` Venus ` may not
117
+ be referenced directly (using ` import Planet.* ` ). You must use an indirect reference,
118
+ such as demonstrated with ` Earth ` .
116
119
117
120
### Deprecation of Enum Cases
118
121
0 commit comments