E131: Lazy Static Field

This error occurs when a lazy val is annotated with @static.

The @static annotation in Scala allows members to be exposed as static fields at the JVM level. However, lazy values cannot be marked as @static because the JVM's static field initialization mechanism is incompatible with Scala's lazy initialization semantics. Lazy vals require wrapper code for thread-safe initialization, which cannot be represented as a simple static field.


Example

import scala.annotation.static

class Example

object Example:
  @static lazy val count: Int = 0

Error

-- [E131] Syntax Error: example.scala:6:19 -------------------------------------
6 |  @static lazy val count: Int = 0
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |  Lazy @static fields are not supported

Solution

// Use a non-lazy @static val
import scala.annotation.static

class Example

object Example:
  @static val count: Int = 0
// Alternative: Keep it lazy but remove @static
import scala.annotation.static

class Example

object Example:
  lazy val count: Int = 0