Back to Scala3

E112: Unable to Extend Sealed Class

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

3.8.41.4 KB
Original Source

E112: Unable to Extend Sealed Class

This error is emitted when attempting to extend a sealed class or trait from a different source file.

Sealed classes and traits can only be extended in the same source file where they are declared. This restriction enables exhaustive pattern matching.


Example

scala
sealed trait Animal
case class Dog(name: String) extends Animal
scala
case class Cat(name: String) extends Animal

Error

scala
-- [E112] Syntax Error: example.scala:1:32
1 |case class Cat(name: String) extends Animal
  |                                     ^^^^^^
  |                     Cannot extend sealed trait Animal in a different source file

Solution

scala
// Define all subclasses in the same file as the sealed trait
sealed trait Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal
scala
// Or use an open or abstract class instead of sealed
abstract class Animal
case class Dog(name: String) extends Animal
// Cat can now be defined in another file
<!-- 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>