With D, how can I pass a function (possibly reference to a function) as an argument to be executed inside other function?
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 = "lorem ipsum";
auto target = new EventTarget();
target.addEventListener("load", (Event event) => { writeln(variableFromParentScope, event); }, true);
}
Gives me the error:
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
I have set up the example here: https://run.dlang.io/is/FnQoId
SOLUTION, With the help from the answers I fixed it like this:
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 = "lorem ipsum";
auto target = new EventTarget();
target.addEventListener(
"load",
(Event event) {
writeln(variableFromParentScope, event);
}
);
}
Working example: https://run.dlang.io/is/6aDRoU