Class initialization

Issue #187 new
Toky Olivier Razanakotonarivo created an issue

Hello,

I like very much the syntax for records bellow:

  TRec = record
    n: Integer;
    t: String;
  end;

  var rec: TRec = (n: 1; t:"OK");

As a javascript user (js codegen), I’d like to request also the same feature for Classes:

 TMyClass = class    
    n: Integer;
    t: String;
  end;

  var cls: TMyClass = (n: 1; t:"OK");

It’s closer to the same syntax in JS with no overhead:

var cls = {n: 1, t: "OK"}

I know the anonymous but it’s longer::

var cls := class
  t: integer = 1;
  t: string = "ok"
end;

Thank you so much

Comments (3)

  1. Eric Grange repo owner

    For the anonymous classes, you can just use the snippet below, with type inference, it is equivalent

    var cls := class
      n := 1;
      t := "ok";
    end;
    

    there is however no naming or typing checks.

    I am unsure about which syntax could be used, without colliding with what “normal” Pascal classes are, and without introducing subtleties when it comes to instantiating the class. If referring an ancestor class in the anonymous class, it brings issues about how the classes should be created, which in JS ranges from “however you wish” to “what framework X usually does, except for classes where we do differently” 🙂

  2. Toky Olivier Razanakotonarivo reporter

    I understand your point. I use always this:

    var cls := class
      n := 1;
      t := "ok";
    end;
    

    But I think It can be simplified. We use it very much in JS so when using JSCodeGen too. If you have many nested classes, it becomes combersome.

    Why not doing like this for Class?

    var cls := new(n: 1, t: "OK");
    

    In Pas2JS, they use an array but difficult to read sometime. I use it too in dwscript:

    function _obj(elts: Array of Variant): Variant;
    var
      c, i: integer;
    begin
      c := elts.Count();
      if (c mod 2) = 0 then begin
        i:=0;
        Result := TVariant.CreateObject;
        while (i<c) do begin
          TVariant.PropertyWrite(Result, TVariant.AsString(elts[i]), elts[i+1]);
          inc(I,2);
        end;
     end else begin
       Result := null;
     end;
    end;
    
    //To use it
    var cls := _obj(
      'n', 1,
      't', 'OK',
    );
    

    But I don’t like too much to have to put string for the property names….

  3. Toky Olivier Razanakotonarivo reporter

    Sorry for _obj function snippet with TVariant and all, I use Jon’s Quartex Pascal.

  4. Log in to comment