|
1 | 1 | ---
|
2 | 2 | layout: doc-page
|
3 |
| -title: "Erased Terms" |
| 3 | +title: "Erased Terms And Classes" |
4 | 4 | ---
|
5 | 5 |
|
| 6 | +`erased` is a modifier that expresses that some definition or expression is erased by the compiler instead of being represented in the compiled output. It is not yet part of the Scala language standard. To enable `erased`, turn on the language feature |
| 7 | +`experimental.erased`. This can be done with a language import |
| 8 | +```scala |
| 9 | +import scala.language.experimental.erased |
| 10 | +``` |
| 11 | +or by setting the command line option `-language:experimental.erased`. |
6 | 12 | ## Why erased terms?
|
7 | 13 |
|
8 | 14 | Let's describe the motivation behind erased terms with an example. In the
|
@@ -187,4 +193,36 @@ end Machine
|
187 | 193 | m.turnOn().turnOn() // error: Turning on an already turned on machine
|
188 | 194 | ```
|
189 | 195 |
|
| 196 | +## Erased Classes |
| 197 | + |
| 198 | +`erased` can also be used as a modifier for a class. An erased class is intended to be used only in erased definitions. If the type of a val definition or parameter is |
| 199 | +a (possibly aliased, refined, or instantiated) erased class, the definition is assumed to be `erased` itself. Likewise, a method with an erased class return type is assumed to be `erased` itself. Since given instances expand to vals and defs, they are also assumed to be erased if the type they produce is an erased class. Finally |
| 200 | +function types with erased classes as arguments turn into erased function types. |
| 201 | + |
| 202 | +Example: |
| 203 | +```scala |
| 204 | +erased class CanRead |
| 205 | + |
| 206 | +val x: CanRead = ... // `x` is turned into an erased val |
| 207 | +val y: CanRead => Int = ... // the function is turned into an erased function |
| 208 | +def f(x: CanRead) = ... // `f` takes an erased parameter |
| 209 | +def g(): CanRead = ... // `g` is turned into an erased def |
| 210 | +given CanRead = ... // the anonymous given is assumed to be erased |
| 211 | +``` |
| 212 | +The code above expands to |
| 213 | +```scala |
| 214 | +erased class CanRead |
| 215 | + |
| 216 | +erased val x: CanRead = ... |
| 217 | +val y: (erased CanRead) => Int = ... |
| 218 | +def f(erased x: CanRead) = ... |
| 219 | +erased def g(): CanRead = ... |
| 220 | +erased given CanRead = ... |
| 221 | +``` |
| 222 | +After erasure, it is checked that no references to values of erased classes remain and that no instances of erased classes are created. So the following would be an error: |
| 223 | +```scala |
| 224 | +val err: Any = CanRead() // error: illegal reference to erased class CanRead |
| 225 | +``` |
| 226 | +Here, the type of `err` is `Any`, so `err` is not considered erased. Yet its initializing value is a reference to the erased class `CanRead`. |
| 227 | + |
190 | 228 | [More Details](./erased-terms-spec.md)
|
0 commit comments