Skip to content

Example accessing enum companion #14142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 23, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/_docs/reference/enums/enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ enum Planet(mass: Double, radius: Double):
end Planet
```

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

```scala
Expand All @@ -89,6 +90,33 @@ object Planet:
end Planet
```

### Restrictions on Enum Cases

Enum case declarations are similar to secondary constructors:
they are scoped outside of the enum template, despite being declared within it.
This means that enum case declarations cannot access inner members of the
enum class.

Similarly, enum case declarations may not directly reference members of the enum's companion object,
even if they are imported (directly, or by renaming). For example:

```scala
import Planet.*
enum Planet(mass: Double, radius: Double):
private final val (MercuryMass @ _, MercuryRadius @ _) = (3.303e+23, 2.4397e6)

case Mercury extends Planet(MercuryMass, MercuryRadius) // Not found
case Venus extends Planet(VenusMass, VenusRadius) // illegal reference
case Earth extends Planet(Planet.EarthMass, Planet.EarthRadius) // ok
object Planet:
private final val (VenusMass @ _, VenusRadius @ _) = (4.869e+24, 6.0518e6)
private final val (EarthMass @ _, EarthRadius @ _) = (5.976e+24, 6.37814e6)
end Planet
```
The fields referenced by `Mercury` are not visible, and the fields referenced by `Venus` may not
be referenced directly (using `import Planet.*`). You must use an indirect reference,
such as demonstrated with `Earth`.

### Deprecation of Enum Cases

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.
Expand Down