<div dir="ltr"><div>I'm finding it extremely inconvenient to write @nogc event-driven code when I can't use lambdas because they always want to allocate closures when they shouldn't be.</div><div><br></div><div>Can anyone take a look at this issue: <a href="https://issues.dlang.org/show_bug.cgi?id=24838">https://issues.dlang.org/show_bug.cgi?id=24838</a></div><div><br></div><div>The problem is this:</div><div><br></div><div>
<pre class="gmail-bz_comment_text" id="gmail-comment_text_0">class MyClass
{
void doSomething();
void myMethod() @nogc
{
acceptsCallback(¬Lambda); // this works; delegate is created from the method
acceptsCallback((){ doSomething(); }); // doesn't work! closure needlessly tries to allocate
}
void notLambda()
{
doSomething();
}
}</pre>
</div><div><br></div><div>Here we have a method that calls some kind of async that receives a callback.</div><div>Obviously, I can pass a method at a callback as shown in the first line of myMethod; but the second line, where I pass the same code as a lambda fails.</div><div><br></div><div>The problem here is that the language is trying to allocate a closure around `this` because the lambda calls another method.</div><div>This is totally redundant; there's no need to allocate a closure if `this` is the only thing that's captured... because it should just accept `this` as the context directly!</div><div>This lambda isn't a closure, it's a METHOD.</div><div>The compiler needs to determine that `this` is the only capture, and then abandon the closure and synthesise the lambda as a regular method.</div><div><br></div><div>This will make lambda's about 100x more useful in <a class="gmail_plusreply" id="plusReplyChip-5">@nogc cod</a>e. And even if you don't care about @nogc; it also eliminates a common source of garbage, and a pointless double-indirection when accessing `this` via another redundant `this`.<br></div><div><br></div><div>I can't think of any time I've ever written a lambda that I actually <i>want</i> to allocate a closure to access latent local scope data, but I almost always refer to sibling members of the calling function to implement some sort of callback response.</div></div>