E130: Trait Companion With Mutable Static — 트레이트 컴패니언의 가변 static
E130: Trait Companion With Mutable Static — 트레이트 컴패니언의 가변 static
트레이트의 컴패니언 객체가 @static 어노테이션을 붙인 가변 필드를 정의할 때 발생하는 에러예요.
본문
트레이트의 컴패니언 객체가 @static 어노테이션을 붙인 가변 필드를 정의할 때 발생해요.
Scala의 @static 어노테이션은 멤버를 JVM 레벨의 static 멤버로 노출시켜줘요. 하지만 트레이트의 컴패니언 객체에서는 초기화 순서의 복잡성과 JVM의 스레드 안전성 문제 때문에, 가변 @static 필드(var로 선언된 것)를 허용하지 않아요.
예시
import scala.annotation.static
trait Example
object Example:
@static var count: Int = 0
에러
-- [E130] Syntax Error: example.scala:6:14 -------------------------------------
6 | @static var count: Int = 0
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
| Companion of traits cannot define mutable @static fields
해결 방법
불변(immutable) @static val을 쓰면 돼요.
// Use an immutable @static val instead
import scala.annotation.static
trait Example
object Example:
@static val count: Int = 0
트레이트 컴패니언 대신 클래스 컴패니언을 쓰는 방법도 있어요.
// Alternative: Use a class companion instead of a trait companion
import scala.annotation.static
class Example
object Example:
@static var count: Int = 0
static이 아니라 일반 가변 필드로 써도 되고요.
// Alternative: Use a non-static mutable field
import scala.annotation.static
trait Example
object Example:
var count: Int = 0