Back to Scala3

E128: Member With Same Name As Static

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

3.8.41.6 KB
Original Source

E128: Member With Same Name As Static

This error occurs when a companion class defines a member with the same name as a @static member in the companion object.

The @static annotation in Scala allows members to be exposed as static members at the JVM level. When a companion object has a @static member, the companion class cannot have a member with the same name because this would create a naming conflict in the generated bytecode.


Example

scala
import scala.annotation.static

class Example:
  val count: Int = 1

object Example:
  @static val count: Int = 0

Error

scala
-- [E128] Syntax Error: example.scala:7:14 -------------------------------------
7 |  @static val count: Int = 0
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^
  |Companion classes cannot define members with same name as a @static member

Solution

scala
// Rename the @static member in the companion object to avoid conflict
import scala.annotation.static

class Example:
  val count: Int = 1

object Example:
  @static val defaultCount: Int = 0
scala
// Alternative: Rename the member in the companion class
import scala.annotation.static

class Example:
  val instanceCount: Int = 1

object Example:
  @static val count: Int = 0
<!-- 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>