Show me how to make a Repository class extensible so that InMemoryRepository can inherit from it without triggering E05030.

← Classes and OOP · Ref: Q1250

EK9 classes are CLOSED by default. To allow another class to extend them, add 'as open' to the parent class declaration. Without 'as open' the compiler raises E05030 'not open to be extended'.

PARENT CLASS AS OPEN

  Repository as open
    name as String: "<unnamed>"
    default Repository()

CHILD CLASS EXTENDS

  InMemoryRepository extends Repository
    default InMemoryRepository()

The 'extends' keyword only compiles if the parent has 'as open' (or is abstract — see Q1251). Any other class declaration is closed and produces E05030 when something tries to inherit from it.

WHEN TO USE 'AS OPEN'

Use 'as open' when you have a CONCRETE base class with a working default behaviour, and you WANT subclasses to provide alternative behaviour while still being usable on their own.

See Q1043 for diagnosing E05030. See Q784 for closed-by-default rationale. See Q1251 for abstract classes as an alternative.

Example

defines module qa.classesandoop.openrepository

  defines class

    Repository as open
      name as String: "<unnamed>"

      default Repository()

      describe() as pure
        <- rtn as String: "Repository: " + name

      default operator ?

    InMemoryRepository extends Repository
      itemCount as Integer: 0

      default InMemoryRepository()

      override describe() as pure
        <- rtn as String: `InMemoryRepository with ${itemCount} items`

      default operator ?

  defines program

    OpenRepositoryDemo()
      stdout <- Stdout()

      repo <- InMemoryRepository()
      stdout.println(repo.describe())

Common mistakes

E05030 — Without 'as open', Repository is closed and InMemoryRepository cannot extend it. Add 'as open' to the parent declaration. See ek9 -h E05030 for details.

Incorrect:

Repository

Correct:

Repository as open
Other ways to ask this
  • How do I mark a Repository class as extensible in EK9?
  • Create a Repository parent class that an InMemoryRepository can extend.
  • I got E05030 on Repository — how do I allow InMemoryRepository to extend it?
  • Make a Repository class open so other repositories can inherit from it.

Coming from another language?

Java: classes open by default, use 'final' to close. Kotlin: closed by default, use 'open' keyword (same as EK9). Scala: classes open by default, use 'final' to close. C#: classes open by default, use 'sealed' to close. Swift: classes open by default, use 'final' to close. EK9: closed by default like Kotlin, 'as open' to allow extension.

Keywords: inheritance, Repository, extensible, extends, closed, E05030, as open