Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Copy/modify initialization expression - with? #135

Open
titzer opened this issue Feb 23, 2023 · 0 comments
Open

Copy/modify initialization expression - with? #135

titzer opened this issue Feb 23, 2023 · 0 comments

Comments

@titzer
Copy link
Owner

titzer commented Feb 23, 2023

    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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant