E136: Static Fields Should Precede Non-Static

This error occurs when a @static field is defined after non-static fields in a companion object.

The @static annotation causes fields to be initialized during class loading, while non-static fields are initialized only when the object is first accessed. To avoid surprises in initialization order, Scala requires all @static fields to be declared before any non-static fields in the same object.


Example

import scala.annotation.static

class Example

object Example:
  val nonStatic: Int = 1
  @static val staticField: Int = 2

Error

-- [E136] Syntax Error: example.scala:7:14 -------------------------------------
7 |  @static val staticField: Int = 2
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |@static value staticField in object Example must be defined before non-static fields.
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The fields annotated with @static should precede any non @static fields.
  | This ensures that we do not introduce surprises for users in initialization order of this class.
  | Static field are initialized when class loading the code of Foo.
  | Non static fields are only initialized the first  time that Foo is accessed.
  |
  | The definition of staticField should have been before the non @static vals:
  | object Example {
  |                       |  @static val staticField = ...
  |                       |  val nonStatic = ...
  |                       |  ...
  |                       |}
   -----------------------------------------------------------------------------

Solution

// Move @static fields before non-static fields
import scala.annotation.static

class Example

object Example:
  @static val staticField: Int = 2
  val nonStatic: Int = 1