Skip to content

Commit e2f32fd

Browse files
authored
Merge pull request #14142 from som-snytt/doc/enum-example
Example accessing enum companion
2 parents 48c65c4 + f00102c commit e2f32fd

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

docs/_docs/reference/enums/enums.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ enum Planet(mass: Double, radius: Double):
7777
end Planet
7878
```
7979

80+
### User-defined companion object of enums
8081
It is also possible to define an explicit companion object for an enum:
8182

8283
```scala
@@ -89,6 +90,33 @@ object Planet:
8990
end Planet
9091
```
9192

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

94122
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)