lambda syntax with curly braces

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 10 07:05:29 PDT 2015


On Monday, 10 August 2015 at 13:57:50 UTC, sigod wrote:
> From docs:
>> The following part => AssignExpression is rewritten to 
>> FunctionLiteralBody:
>> { return AssignExpression ; }
>
> So, I wonder what happens when curly braces already in place?

It does exactly what that says: rewrites it to

(a) {
   return {
        writeln(a);
   };
}


which is returning a delegate.

> This code compiles and doesn't output anything.

So your code passed a delegate that returned a delegate to each. 
Since the one returned wasn't called, the writeln never happened.

If you call it like so:

     [1,2,3,4,5]
         .each!(a => {
             writeln(a);
         }()); // added parens call the returned delegate

then you see it.




The => thing in D is meant only for trivial, single line things. 
If you want multiple lines, that's where the {} syntax comes in 
with no need for the =>.

.each!( (a) {
        writeln(a);
   });


More information about the Digitalmars-d-learn mailing list