Create Dynamic Class

Create Dynamic Class authors a class - a local variable holding a small object, declared where you are, with no construct of its own to name - implementing one or more traits you pick, extending a generic base, or naming a module-level tuple type; the compiler validates the result in the same preview every refactoring opens. Here Labeler has nothing that knows how to describe its own item. To play it in the IDE: Help > Lessons > Writing code…, or ek9 -ide -lesson create-dynamic-class.

The EK9 IDE as the lesson opens

Start from

The code the lesson starts from: copy it into a file of your own and follow the steps.

#!ek9
defines module lesson.dyncls

  defines trait

    Describable
      describe() as pure abstract
        <- rtn as String?

  defines program

    Labeler()
      stdout <- Stdout()
      prefix <- "item"
      stdout.println(prefix)

//EOF

Step 1: Where it goes

Put the caret at the end of the prefix <- "item" line - the class is inserted straight after it.

The EK9 IDE once this is done: Put the caret at the end of the prefix <- "item" line - the class is inserted straight after it

Step 2: Create the class

Right-click it - or choose Refactor > Refactor This… - and choose Create Dynamic Class…. Name the variable d, add a trait row named Describable - trait is already the chosen form - choose Generate trait methods to stub describe(), and choose Preview.

The EK9 IDE just before choosing Preview: Right-click it - or choose Refactor > Refactor This… - and choose Create Dynamic Class…

Step 3: Preview and apply

The preview shows the class; then the IDE formats the file it changed. Choose Apply.

The EK9 IDE just before choosing Apply: The preview shows the class; then the IDE formats the file it changed

Step 4: Use it

An instance never used is a local EK9 refuses (E08090) - replace stdout.println(prefix) with stdout.println(prefix + d.describe()) and save.

The EK9 IDE once this is done: An instance never used is a local EK9 refuses (E08090) - replace stdout.println(prefix) with stdout.println(prefix + d.describe()) and save

The result

That is Create Dynamic Class: d is an anonymous class implementing Describable, its one abstract method describe() stubbed by Generate trait methods with a //AI: complete method lead - and prefix's println now reads it too. The same Form selector offers tuple (a named module-level type, captures allowed instead of members) and generic (extending a parameterised base like Iterator of Integer) - try one yourself; delegating a trait to a captured field instead of implementing it is the same idea Generate Delegation plays on a named class. It is on the right-click menu, and on Code ▸ Create Dynamic Class…, wherever the caret is inside a function, program or method body; AI assistants use the ek9_create_dynamic_class tool.

Where this lesson comes from