Back to Scala3

E073: Value Classes May Not Contain Initialization

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

3.8.41.5 KB
Original Source

E073: Value Classes May Not Contain Initialization

This error is emitted when a value class (a class extending AnyVal) contains initialization statements in its body.

Value classes may not contain initialization statements because they are meant to be completely inlined by the compiler. Any initialization code would prevent this optimization.


Example

scala
class Wrapper(val value: Int) extends AnyVal:
  println(s"Created wrapper with $value")

Error

scala
-- [E073] Syntax Error: example.scala:2:9 --------------------------------------
2 |  println(s"Created wrapper with $value")
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |  Value classes may not contain initialization statements

Solution

scala
// Remove initialization statements
class Wrapper(val value: Int) extends AnyVal:
  def show: String = s"Wrapper($value)"
scala
// Or use a companion object for factory logic
class Wrapper(val value: Int) extends AnyVal

object Wrapper:
  def create(value: Int): Wrapper =
    println(s"Creating wrapper with $value")
    new Wrapper(value)
scala
// Or use a regular class if you need initialization
class Wrapper(val value: Int):
  println(s"Created wrapper with $value")
<!-- 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>