Back to Scala3

E132: Static Overriding Non-Static Members

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

3.8.41.6 KB
Original Source

E132: Static Overriding Non-Static Members

This error occurs when a @static member in a companion object tries to override or implement a non-static member from a parent trait or class.

The @static annotation causes a member to be compiled as a JVM static member. Static members cannot participate in inheritance hierarchies because they are not part of instances and cannot be dynamically dispatched. Therefore, a @static member cannot override or implement abstract members from parent types.


Example

scala
import scala.annotation.static

trait Parent:
  def value: Int

class Child

object Child extends Parent:
  @static def value: Int = 42

Error

scala
-- [E132] Syntax Error: example.scala:9:14 -------------------------------------
9 |  @static def value: Int = 42
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |  @static members cannot override or implement non-static ones

Solution

scala
// Remove the @static annotation to allow proper implementation
import scala.annotation.static

trait Parent:
  def value: Int

class Child

object Child extends Parent:
  def value: Int = 42
scala
// Alternative: Don't extend the trait and use a different method name
import scala.annotation.static

trait Parent:
  def value: Int

class Child

object Child:
  @static def staticValue: Int = 42
<!-- 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>