Back to Scala3

E068: Cannot Extend AnyVal

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

3.8.41.7 KB
Original Source

E068: Cannot Extend AnyVal

This error is emitted when a trait or object attempts to extend AnyVal.

Only classes can extend AnyVal to become value classes. Traits may extend Any to become "universal traits" which may only have def members. Universal traits can be mixed into classes that extend AnyVal.


Example

scala
trait MyValueTrait extends AnyVal

Error

scala
-- [E068] Syntax Error: example.scala:1:6 --------------------------------------
1 |trait MyValueTrait extends AnyVal
  |      ^
  |      trait MyValueTrait cannot extend AnyVal
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | Only classes (not traits) are allowed to extend AnyVal, but traits may extend
  | Any to become "universal traits" which may only have def members.
  | Universal traits can be mixed into classes that extend AnyVal.
   -----------------------------------------------------------------------------

Solution

scala
// Use a class for value classes
class MyValueClass(val value: Int) extends AnyVal
scala
// For traits, extend Any to create a universal trait
trait MyUniversalTrait extends Any:
  def method: Int

class MyValueClass(val value: Int) extends AnyVal with MyUniversalTrait:
  def method: Int = 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>