final 클래스를 상속하려 했어요

final 클래스를 상속하려 했어요 (E093: Extend Final Class)

final로 표시된 클래스를 상속하려 하면 이 에러가 나요. final 키워드가 붙은 클래스는 다른 클래스가 상속할 수 없어요.

출처: Scala 3 Reference

본문

final로 표시된 클래스를 상속하려 하면 이 에러가 발생해요.

final 키워드가 붙은 클래스는 다른 어떤 클래스도 상속할 수 없어요. 클래스 설계가 서브클래싱(subclassing)을 지원하지 않거나 의도하지 않았을 때 상속을 막기 위한 장치예요.

예시 (Example)

final class Parent

class Child extends Parent

에러 (Error)

-- [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)

상속이 의도된 것이라면 부모 클래스에서 final을 빼면 돼요.

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

class Child extends Parent

상속 대신 컴포지션(composition)을 쓰는 방법도 있어요.

// 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