Back to Scala3

E052: Reassignment To Val

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

3.8.41.7 KB
Original Source

E052: Reassignment To Val

This error is emitted when attempting to reassign a value to an immutable variable declared with val.

You cannot assign a new value to a val as values cannot be changed after initialization. Reassignment is only permitted if the variable is declared with var.

If you're seeing this error in a boolean context, you may have accidentally used = (assignment) instead of == (equality test).


Example

scala
def example =
  val x = 1
  x = 2

Error

scala
-- [E052] Type Error: example.scala:3:4 ----------------------------------------
3 |  x = 2
  |  ^^^^^
  |  Reassignment to val x
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | You can not assign a new value to x as values can't be changed.
  | Reassigment is only permitted if the variable is declared with `var`.
   -----------------------------------------------------------------------------

Solution

scala
// Use var if you need to reassign
def example =
  var x = 1
  x = 2
scala
// Or use a new val with a different name
def example =
  val x = 1
  val y = 2
scala
// If you meant to compare values, use ==
def example =
  val x = 1
  val isTwo = x == 2
<!-- 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>