Back to Scala3

E109: Static Fields Only Allowed in Objects

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

3.8.41.5 KB
Original Source

E109: Static Fields Only Allowed in Objects

This error is emitted when the @static annotation is used on a member that is not inside an object.

The @static annotation can only be applied to members defined within a Scala object, not in classes or traits.


Example

scala
import scala.annotation.static

class Example:
  @static val count = 0

Error

scala
-- [E109] Syntax Error: example.scala:4:14 -------------------------------------
4 |  @static val count = 0
  |  ^^^^^^^^^^^^^^^^^^^^^
  |@static value count in class Example must be defined inside a static object.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | @static members are only allowed inside objects.
   -----------------------------------------------------------------------------

Solution

scala
// Move the @static member to an object
import scala.annotation.static

class Example

object Example:
  @static val count = 0
scala
// Or remove @static if you don't need static behavior
class Example:
  val count = 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>