Back to Scala3

E157: Cannot Extend Java Enum

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

3.8.41.3 KB
Original Source

E157: Cannot Extend Java Enum

This error occurs when a class tries to extend java.lang.Enum directly. In Scala 3, only enums defined with the enum syntax are allowed to extend Java's Enum class.

This restriction ensures that Scala enums follow proper semantics and benefit from compiler support for exhaustiveness checking and other enum-specific features.


Example

scala
class MyEnum extends java.lang.Enum[MyEnum]

Error

scala
-- [E157] Syntax Error: example.scala:1:6 --------------------------------------
1 |class MyEnum extends java.lang.Enum[MyEnum]
  |      ^
  |class MyEnum cannot extend java.lang.Enum: only enums defined with the enum syntax can

Solution

scala
// Use Scala 3 enum syntax instead
enum MyEnum {
  case Value1, Value2, Value3
}
scala
// For Java interop, Scala 3 enums automatically extend java.lang.Enum
enum Color {
  case Red, Green, Blue
}

// Color cases are instances of java.lang.Enum[Color]
<!-- 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>