title: D (dlang) passing a lambda function as argument
body: <p>With D, how can I pass a function (possibly reference to a function) as an argument to be executed inside other function?</p>
  <pre class="lang-d prettyprint-override"><code>import std.stdio : writeln;
  
  class Event {}
  
  class EventTarget
  {
      void addEventListener(string eventName, void delegate(Event event) callback)
      {
          // TODO: add to slice to execute later, for now execute directly
          callback();
      }
  }
  
  void main()
  {
      auto variableFromParentScope = &quot;lorem ipsum&quot;;
      auto target = new EventTarget();
      target.addEventListener(&quot;load&quot;, (Event event) =&gt; { writeln(variableFromParentScope, event); }, true);
  }
  </code></pre>
  <p>Gives me the error:</p>
  <pre><code>onlineapp.d(10): Error: delegate callback(Event event) is not callable using argument types ()
  onlineapp.d(10):        missing argument for parameter #1: Event event
  onlineapp.d(18): Error: function onlineapp.EventTarget.addEventListener(string eventName, void delegate(Event event) callback) is not callable using argument types (string, void delegate() @system delegate(Event event) pure nothrow @safe, bool)
  onlineapp.d(18):        cannot pass argument __lambda1 of type void delegate() @system delegate(Event event) pure nothrow @safe to parameter void delegate(Event event) callback
  </code></pre>
  <p>I have set up the example here: <a href="https://run.dlang.io/is/FnQoId" rel="nofollow noreferrer">https://run.dlang.io/is/FnQoId</a></p>
  <hr />
  <p>SOLUTION, With the help from the answers I fixed it like this:</p>
  <pre class="lang-d prettyprint-override"><code>import std.stdio : writeln;
  
  class Event {}
  
  class EventTarget
  {
      void addEventListener(string eventName, void delegate(Event event) callback)
      {
          // TODO: add to slice to execute later, for now execute directly
          callback(new Event());
      }
  }
  
  void main()
  {
      auto variableFromParentScope = &quot;lorem ipsum&quot;;
      auto target = new EventTarget();
      target.addEventListener(
          &quot;load&quot;, 
          (Event event) {
              writeln(variableFromParentScope, event);
          }
      );
  }
  </code></pre>
  <p>Working example: <a href="https://run.dlang.io/is/6aDRoU" rel="nofollow noreferrer">https://run.dlang.io/is/6aDRoU</a></p>