Generate Delegation

Generate Delegation wires a trait the class already declares to an existing field with 'by' and the field's name, so the compiler forwards every trait method to it - no bodies to write. Here Robot declares Greeter but has not yet delegated it, so greet() falls back to the trait's own default ('Hello'); inner, an EchoGreeter, is Robot's only field. To play it in the IDE: Help > Lessons > Refactoring…, or ek9 -ide -lesson generate-delegation.

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.delegate

  defines trait

    Greeter
      greet() as pure
        <- rtn as String: "Hello"

  defines class

    EchoGreeter with trait of Greeter

      override greet() as pure
        <- rtn as String: "Echo"

    Robot with trait of Greeter

      inner as EchoGreeter: EchoGreeter()
      default operator ?

  defines program

    Show()
      stdout <- Stdout()
      robot <- Robot()
      stdout.println(robot.greet())

//EOF

Step 1: Where it is

Put the caret on Robot, on line 17.

The EK9 IDE once this is done: Put the caret on Robot, on line 17

Step 2: Generate Delegation

Right-click it - or choose Refactor > Refactor This… - and choose Generate Delegation…

The EK9 IDE once this is done: Right-click it - or choose Refactor > Refactor This… - and choose Generate Delegation…

Greeter and inner are already chosen - Robot's only trait and only field. Choose Preview.

Step 3: Preview and apply

The preview shows every change the refactoring makes; then the IDE formats each file it changed. Choose Apply.

The EK9 IDE just before choosing Apply: The preview shows every change the refactoring makes; then the IDE formats each file it changed

The result

That is Generate Delegation: Robot now reads 'with trait of Greeter by inner', so greet() forwards to inner and returns 'Echo' instead of the trait's own 'Hello'. Wiring a trait the class does NOT yet declare is Adopt Trait's delegate mode instead; overriding one forwarded method yourself (Add Method) simply shadows it. It is on the right-click menu wherever the caret is inside a class that declares an undelegated trait and owns a field; AI assistants use the ek9_generate_delegation tool.

The EK9 IDE when the lesson has finished

Where this lesson comes from