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

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

Error

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

Solution

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