Back to Scala3

E093: Extend Final Class

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

3.8.41.5 KB
Original Source

E093: Extend Final Class

This error is emitted when attempting to extend a class that is marked as final.

A class marked with the final keyword cannot be extended by any other class. This is used to prevent inheritance when the class design doesn't support or intend for subclassing.


Example

scala
final class Parent

class Child extends Parent

Error

scala
-- [E093] Syntax Error: example.scala:3:6 --------------------------------------
3 |class Child extends Parent
  |      ^
  |      class Child cannot extend final class Parent
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | A class marked with the final keyword cannot be extended
   -----------------------------------------------------------------------------

Solution

scala
// Remove final from the parent if inheritance is intended
class Parent

class Child extends Parent
scala
// Or use composition instead of inheritance
final class Parent:
  def greet: String = "Hello"

class Child:
  private val parent = new Parent
  def greet: String = parent.greet
<!-- 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>