Skip to content

Commit d26c089

Browse files
som-snyttbishabosha
authored andcommitted
Example accessing enum companion
1 parent 48c65c4 commit d26c089

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

docs/_docs/reference/enums/enums.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,31 @@ object Planet:
8989
end Planet
9090
```
9191

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.
96+
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:
99+
100+
```scala
101+
import Planet.*
102+
enum Planet(mass: Double, radius: Double):
103+
private final val (MercuryMass @ _, MercuryRadius @ _) = (3.303e+23, 2.4397e6)
104+
105+
case Mercury extends Planet(MercuryMass, MercuryRadius) // Not found
106+
case Venus extends Planet(VenusMass, VenusRadius) // illegal reference
107+
case Earth extends Planet(Planet.EarthMass, Planet.EarthRadius) // ok
108+
object Planet:
109+
private final val (VenusMass @ _, VenusRadius @ _) = (4.869e+24, 6.0518e6)
110+
private final val (EarthMass @ _, EarthRadius @ _) = (5.976e+24, 6.37814e6)
111+
end Planet
112+
```
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+
92117
### Deprecation of Enum Cases
93118

94119
As a library author, you may want to signal that an enum case is no longer intended for use. However you could still want to gracefully handle the removal of a case from your public API, such as special casing deprecated cases.

0 commit comments

Comments
 (0)