View mode: basic / threaded / horizontal-split · Log in · Help
September 01, 2007
With as an expression instead of a statement
Hi,

I've been playing with D for some time now and I thought of something. It might have been proposed before but I didn't find anything about it.

My idea is to enhance the "with" statement so that it becomes more useful: "with" could be an expression instead of a statement. The value of the expression would be the value of the object passed to the with statement. This could be very useful to initialize complex objects, like in GUI libraries.

Here is an example of what you can do now with "with":

class AClass { ... }

void foo(AClass c) { ... }

AClass c;
with (c = new AClass()) {
  method1 = 10;
  method2 = 100;
  // ...
}
foo(c);

If "with" was an expression, you could write:

auto c = with (new AClass()) {
  method1 = 10;
  method2 = 100;
  // ...
}
foo(c);

Or, if you don't need "c":

foo(with (new AClass()) {
  method1 = 10;
  method2 = 100;
  // ...
});

What do you think?

Guillaume B.
September 01, 2007
Re: With as an expression instead of a statement
Reply to Guillaume B.,

> Hi,
> 
> I've been playing with D for some time now and I thought of something.
> It might have been proposed before but I didn't find anything about
> it.
> 
> My idea is to enhance the "with" statement so that it becomes more
> useful: "with" could be an expression instead of a statement. The
> value of the expression would be the value of the object passed to the
> with statement. This could be very useful to initialize complex
> objects, like in GUI libraries.
> 
> Here is an example of what you can do now with "with":
> 
> class AClass { ... }
> 
> void foo(AClass c) { ... }
> 
> AClass c;
> with (c = new AClass()) {
> method1 = 10;
> method2 = 100;
> // ...
> }
> foo(c);
> 
> If "with" was an expression, you could write:
> 
> auto c = with (new AClass()) {
> method1 = 10;
> method2 = 100;
> // ...
> }
> foo(c);
> 
> Or, if you don't need "c":
> 
> foo(with (new AClass()) {
> method1 = 10;
> method2 = 100;
> // ...
> });
> What do you think?
> 
> Guillaume B.
> 

vote += 0.25;
Top | Discussion index | About this forum | D home