Skip to content

Commit ff96a5d

Browse files
authored
Merge pull request #13822 from dotty-staging/fix-13770
Add explanations to discussion of private[this] in docs
2 parents 2a49471 + d062eac commit ff96a5d

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

docs/docs/reference/dropped-features/this-qualifier.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,26 @@ Previously, these modifiers were needed for
1212

1313
- avoiding the generation of getters and setters
1414
- excluding code under a `private[this]` from variance checks. (Scala 2 also excludes `protected[this]` but this was found to be unsound and was therefore removed).
15+
- avoiding the generation of fields, if a `private[this] val` is not accessed
16+
by a class method.
1517

1618
The compiler now infers for `private` members the fact that they are only accessed via `this`. Such members are treated as if they had been declared `private[this]`. `protected[this]` is dropped without a replacement.
1719

20+
This change can in some cases change the semantics of a Scala program, since a
21+
`private` val is no longer guaranteed to generate a field. The field
22+
is omitted if
23+
24+
- the `val` is only accessed via `this`, and
25+
- the `val` is not accessed from a method in the current class.
26+
27+
This can cause problems if a program tries to access the missing private field via reflection. The recommended fix is to declare the field instead to be qualified private with the enclosing class as qualifier. Example:
28+
```scala
29+
class C(x: Int):
30+
private[C] val field = x + 1
31+
// [C] needed if `field` is to be accessed through reflection
32+
val retained = field * field
33+
```
34+
35+
36+
37+

0 commit comments

Comments
 (0)