Skip to content

Commit d8e4af7

Browse files
authored
Merge pull request #11169 from dotty-staging/update-enum-docs-deprecation
Document deprecation of enum cases
2 parents cc8ffb1 + db4935c commit d8e4af7

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

docs/docs/reference/enums/enums.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,48 @@ object Planet:
8888
end Planet
8989
```
9090

91+
### Deprecation of Enum Cases
92+
93+
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.
94+
95+
To illustrate, say that the `Planet` enum originally had an additional case:
96+
```diff
97+
enum Planet(mass: Double, radius: Double):
98+
...
99+
case Neptune extends Planet(1.024e+26, 2.4746e7)
100+
+ case Pluto extends Planet(1.309e+22, 1.1883e3)
101+
end Planet
102+
```
103+
104+
We now want to deprecate the `Pluto` case. First we add the `scala.deprecated` annotation to `Pluto`:
105+
106+
```diff
107+
enum Planet(mass: Double, radius: Double):
108+
...
109+
case Neptune extends Planet(1.024e+26, 2.4746e7)
110+
- case Pluto extends Planet(1.309e+22, 1.1883e3)
111+
+
112+
+ @deprecated("refer to IAU definition of planet")
113+
+ case Pluto extends Planet(1.309e+22, 1.1883e3)
114+
end Planet
115+
```
116+
117+
Outside the lexical scopes of `enum Planet` or `object Planet`, references to `Planet.Pluto` will produce a deprecation warning, but within those scopes we can still reference it to implement introspection over the deprecated cases:
118+
119+
```scala
120+
trait Deprecations[T <: reflect.Enum] {
121+
extension (t: T) def isDeprecatedCase: Boolean
122+
}
123+
124+
object Planet {
125+
given Deprecations[Planet] with {
126+
extension (p: Planet)
127+
def isDeprecatedCase = p == Pluto
128+
}
129+
}
130+
```
131+
We could imagine that a library may use [type class derivation](../contextual/derivation.md) to automatically provide an instance for `Deprecations`.
132+
91133
### Compatibility with Java Enums
92134
If you want to use the Scala-defined enums as [Java enums](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html), you can do so by extending
93135
the class `java.lang.Enum`, which is imported by default, as follows:

0 commit comments

Comments
 (0)