Back to Scala3

E071: Value Classes May Not Define Non Parameter Field

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

3.8.41.3 KB
Original Source

E071: Value Classes May Not Define Non Parameter Field

This error is emitted when a value class (a class extending AnyVal) defines a val or var field that is not the primary constructor parameter.

Value classes can only have the single val parameter from their primary constructor. Additional fields would require object allocation, defeating the purpose of value classes.


Example

scala
class Wrapper(val value: Int) extends AnyVal:
  val doubled = value * 2

Error

scala
-- [E071] Syntax Error: example.scala:2:6 --------------------------------------
2 |  val doubled = value * 2
  |  ^^^^^^^^^^^^^^^^^^^^^^^
  |  Value classes may not define non-parameter field

Solution

scala
// Use a def instead of val
class Wrapper(val value: Int) extends AnyVal:
  def doubled: Int = value * 2
scala
// Or use a regular class if you need fields
class Wrapper(val value: Int):
  val doubled = value * 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>