Back to Scala3

E131: Lazy Static Field

docs/_docs/reference/error-codes/E131.md

3.8.41.4 KB
Original Source

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

scala
import scala.annotation.static

class Example

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

Error

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

Solution

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

class Example

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

class Example

object Example:
  lazy val count: Int = 0
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>