E136: Static Fields Should Precede Non-Static — static 필드는 비-static보다 앞에 와야 해요

E136: Static Fields Should Precede Non-Static — static 필드는 비-static보다 앞에 와야 해요

컴패니언 객체에서 @static 필드가 비-static 필드보다 뒤에 정의될 때 발생하는 에러예요.

출처: Scala 3 Reference

본문

컴패니언 객체에서 @static 필드가 비-static 필드보다 뒤에 정의될 때 발생해요.

@static 어노테이션이 붙은 필드는 클래스 로딩 중에 초기화되는 반면, 비-static 필드는 객체가 처음 접근될 때 비로소 초기화돼요. 초기화 순서에서 예상치 못한 일이 생기지 않도록, Scala는 같은 객체 안에서 모든 @static 필드가 비-static 필드보다 먼저 선언되도록 요구해요.

예시

import scala.annotation.static

class Example

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

에러

-- [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 = ...
  |                       |  ...
  |                       |}
   -----------------------------------------------------------------------------

해결 방법

@static 필드를 비-static 필드보다 앞으로 옮기면 돼요.

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

class Example

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