Skip to content

Copy/modify initialization expression - with? #135

Description

@titzer
    I am thinking of a construct to make initialization of large, complex structures with named members easier. Some ideas:

with expression

class Config {
  var name: string;
  var size: int;
  var doMore: bool;
  var extraThings: Array<int>;
}

def x = Config.new() with {
  name = "foo";
  size = 44;
  doMore = false;
  extraThings = [88, 99, 1000];
};

The idea of the with expression is that it takes an expression on the left and applies the updates to the fields given in the curlies { ... }. For class types with mutable members, it takes an object, mutates the original object and returns it. For tuples, data types, or ADTs, it would create a new value with the updated fields.

It allows for having lots of parameters via a config object:

class Args { ... }
def m(x: Args) {
  ...
}
var r1 = m(Args.new() with { name = "string"; size = 66; });
// or, eliding the .new():
var r2 = m(Args with {name = "myname"; size = 777; });

Wdyt?

Originally posted by @titzer in #122 (comment)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions