www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - With as an expression instead of a statement

reply Guillaume B. <guillaume.b.spam spam.spam> writes:
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.
Sep 01 2007
parent BCS <ao pathlink.com> writes:
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;
Sep 01 2007