Convert Constructor

Convert Constructor swaps a no-arg constructor between its two equivalent forms: 'default Name()' - the compiler's own shorthand - and an explicit body that sets every field with :=?. Here Person's no-arg constructor is 'default private', with nothing to customise yet. To play it in the IDE: Help > Lessons > Refactoring…, or ek9 -ide -lesson convert-constructor.

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

  defines record

    Person
      firstName as String?
      lastName as String?

      default private Person() as pure

      Person() as pure
        ->
          firstName as String
          lastName as String

        this.firstName :=? firstName
        this.lastName :=? lastName

      default operator ?

  defines program

    ShowPerson()
      stdout <- Stdout()
      person <- Person("Ada", "Lovelace")
      stdout.println(`${person.firstName} ${person.lastName}`)

//EOF

Step 1: The constructor

Put the caret on the default private Person() as pure line.

The EK9 IDE once this is done: Put the caret on the default private Person() as pure line

Step 2: Expand it

Right-click it and choose Expand 'default' Constructor to Default-Setter.

The EK9 IDE once this is done: Right-click it and choose Expand 'default' Constructor to Default-Setter

The change is in the open file, not yet saved. Choose File > Save.

The EK9 IDE once this is done: The change is in the open file, not yet saved

The result

That is Convert Constructor: Person's no-arg constructor is now explicit - private Person() as pure - with one this.field :=? String() per assignable field, ready to customise (add validation before the fields are set, say). Collapse Constructor to 'default' is the exact reverse, offered instead on an explicit no-arg constructor once its body has converged back to what the compiler would generate anyway - collapsing it removes the noise, and the next field added is picked up automatically. Both sit on the right-click menu wherever the caret is on a no-arg constructor's own declaration line; AI assistants use the ek9_convert_constructor tool (mode is inferred from the constructor found).

Where this lesson comes from