Skip to content

Add explanations to discussion of private[this] in docs #13822

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 1 commit into from
Oct 27, 2021
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
20 changes: 20 additions & 0 deletions docs/docs/reference/dropped-features/this-qualifier.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ Previously, these modifiers were needed for

- avoiding the generation of getters and setters
- 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).
- avoiding the generation of fields, if a `private[this] val` is not accessed
by a class method.

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.

This change can in some cases change the semantics of a Scala program, since a
`private` val is no longer guaranteed to generate a field. The field
is omitted if

- the `val` is only accessed via `this`, and
- the `val` is not accessed from a method in the current class.

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:
```scala
class C(x: Int):
private[C] val field = x + 1
// [C] needed if `field` is to be accessed through reflection
val retained = field * field
```