E039: Forward Reference Extends Over Definition — 전방 참조가 다른 값의 정의를 가로질러요
E039: Forward Reference Extends Over Definition — 전방 참조가 다른 값의 정의를 가로질러요
어떤 값에 대한 전방 참조(forward reference) 가 다른 값의 정의를 가로질러 확장될 때 이 에러가 나와요.
본문
전방 참조는 참조하는 지점과 참조 대상의 정의 사이에 다른 값 정의가 없을 때만 허용돼요. 구체적으로, 참조와 정의 사이에 있는 어떤 문장도 변수 정의여서는 안 되고, 값 정의라면 반드시 lazy여야 해요.
예제 (Example)
def example =
def a: Int = b
val b: Int = a
a
a 안에서 b를 쓰는데, 그 사이에 b의 정의(val b)가 있어요. 그래서 전방 참조가 정의를 가로지르게 됐죠.
오류 메시지 (Error)
-- [E039] Reference Error: example.scala:2:17 ----------------------------------
2 | def a: Int = b
| ^
| forward reference to b extends over the definition of b (on line 3)
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| b is used before you define it, and the definition of b
| appears between that use and the definition of b.
|
| Forward references are allowed only if there are no value definitions between
| the reference and the definition that is referred to.
| Specifically, any statement between the reference and the definition
| cannot be a variable definition, and if it's a value definition, it must be lazy.
|
| Define b before it is used,
| or move the definition of b so it does not appear between
| the declaration of b and its use,
| or define b as lazy.
-----------------------------------------------------------------------------
해결 방법 (Solution)
전방 의존성을 lazy로 만들거나, 의존성 체인을 아예 끊어 주는 게 좋아요.
// Make the forward dependency lazy
// Warning: It still might fail at runtime
def example =
def a: Int = b
lazy val b: Int = a
a
// Even better ensure to always break the dependecny chain
def example =
lazy val a: Int = if b == 0 then 1 else b
lazy val b: Int = 0
a