E130: Trait Companion With Mutable Static
This error occurs when a companion object of a trait defines a mutable field with the @static annotation.
The @static annotation in Scala allows members to be exposed as static members at the JVM level. However, mutable @static fields (declared with var) are not allowed in companion objects of traits due to initialization order complexities and thread-safety concerns in the JVM.
Example
import scala.annotation.static
trait Example
object Example:
@static var count: Int = 0
Error
-- [E130] Syntax Error: example.scala:6:14 -------------------------------------
6 | @static var count: Int = 0
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
| Companion of traits cannot define mutable @static fields
Solution
// 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
// Alternative: Use a non-static mutable field
import scala.annotation.static
trait Example
object Example:
var count: Int = 0
In this article