Back to Scala3

E227: Private Shadows Type

docs/_docs/reference/error-codes/E227.md

3.8.41.7 KB
Original Source

E227: Private Shadows Type

This warning is emitted when a private field shadows an inherited field with the same name.

Shadowing inherited fields can make code harder to understand because references in the subclass may no longer refer to the member from the parent type.

This warning is enabled with the -Wshadow:private-shadow compiler flag.


Example

scala
class Parent:
  val value = 1

class Child extends Parent:
  private val value = 2

Warning

scala
-- [E227] Naming Warning: example.scala:5:2 ------------------------------------
5 |  private val value = 2
  |  ^
  |  value value shadows field value inherited from class Parent
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | A private field shadows an inherited field with the same name.
  | This can lead to confusion as the inherited field becomes inaccessible.
  | Consider renaming the private field to avoid the shadowing.
   -----------------------------------------------------------------------------

Solution

Rename the private field so it no longer shadows the inherited one:

scala
class Parent:
  val value = 1

class Child extends Parent:
  private val localValue = 2
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>