Back to Scala3

E206: Enum May Not Be Value Class

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

3.8.41.4 KB
Original Source

E206: Enum May Not Be Value Class

This error occurs when attempting to define an enum that extends AnyVal. Enums cannot be value classes in Scala 3.

Value classes are a mechanism for defining types that avoid runtime object allocation, but this is incompatible with the way enums are implemented in Scala 3. Enums require a class hierarchy to represent their cases, which is not possible with value classes.

Example

scala
enum Orientation extends AnyVal:
  case North, South, East, West

Error

scala
-- [E206] Syntax Error: example.scala:1:5 --------------------------------------
1 |enum Orientation extends AnyVal:
  |     ^
  |     class Orientation may not be a value class

Solution

Remove the extends AnyVal clause from the enum definition:

scala
enum Orientation:
  case North, South, East, West

If you need a lightweight representation for performance reasons, consider using an opaque type instead:

scala
object Orientation:
  opaque type Orientation = Int
  val North: Orientation = 0
  val South: Orientation = 1
  val East: Orientation = 2
  val West: Orientation = 3
<!-- 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>