Back to Scala3

E193: Volatile on Val

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

3.8.41.2 KB
Original Source

E193: Volatile on Val

This warning is emitted when the @volatile annotation is applied to a val (immutable value).

The @volatile annotation is meaningful only for mutable fields (var) because it ensures visibility of changes across threads. Since val is immutable and can only be assigned once during initialization, the volatile annotation has no effect and is likely a mistake.


Example

scala
class Example:
  @volatile val x: Int = 42

Error

scala
-- [E193] Syntax Warning: example.scala:2:16 -----------------------------------
2 |  @volatile val x: Int = 42
  |                ^
  |                values cannot be volatile

Solution

If you need a volatile field, use var:

scala
class Example:
  @volatile var x: Int = 42

If the value should be immutable, remove the @volatile annotation:

scala
class Example:
  val x: Int = 42
<!-- 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>