Back to Scala3

E072: Value Classes May Not Define A Secondary Constructor

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

3.8.41.4 KB
Original Source

E072: Value Classes May Not Define A Secondary Constructor

This error is emitted when a value class (a class extending AnyVal) defines a secondary constructor.

Value classes can only have one primary constructor with exactly one val parameter. Secondary constructors are not allowed because they would complicate the optimization of value classes.


Example

scala
class Wrapper(val value: Int) extends AnyVal:
  def this(s: String) = this(s.toInt)

Error

scala
-- [E072] Syntax Error: example.scala:2:6 --------------------------------------
2 |  def this(s: String) = this(s.toInt)
  |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |  Value classes may not define a secondary constructor

Solution

scala
// Use a companion object factory method instead
class Wrapper(val value: Int) extends AnyVal

object Wrapper:
  def fromString(s: String): Wrapper = new Wrapper(s.toInt)
scala
// Or use a regular class if you need multiple constructors
class Wrapper(val value: Int):
  def this(s: String) = this(s.toInt)
<!-- 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>