Now Marry comes along and is asked to stick the two together without subclassing or changing any of code. Luckily Peter was foresightful and added use Signal; right at the top of his code. That allowed him to add is signal to an empty method (that does nothing indeed).

Marry quickly connects some empty methods of Peter’s classes with Paul’s Person class. How does that work? Let’s have a look at some simplified code (the real thing is linked at the bottom). It all starts with a role.

And here is the magic. What we do is to take a Routine (sub or pointy block) and apply a trait to it, like so.

sub my_signal is signal() { #` this wont be called` }

That calls traid_mod:<is>, which does a mixin of the Routine with Signal and creates a wrapper around my_signal that loops over all connected slots and calls them one after another. If there are arguments to the signal call, they are passed on. Thanks to the mixin we can connect our signal now to as many subs as we want.

The last line will call the two subs one after another. There can be as many callbacks per signal as rakudo can manage and there is no need to fiddle with handles when it comes to remove a callback from a signal. Any signal can be made fully introspective and as soon as &f.signature ~~ &some_sub_a.signature works type checks can be done when a signal is connected.

So why is this cool. Have a look back into Peter’s code in the fake_event_handler. Peter is calling a signal in the last line of that method. That doesn’t do anything until Marry comes along and connects it to Paul’s Person class. Our three friends don’t have to talk to each other to make that happen, thanks to the foresighted Paul who decided to leave some methods empty. There is no subclassing required (quite in contrast to the Qt) to make that work in Perl 6 what makes interfaces a little less fragile.

The whole thing can be found here and will end up on github as a module after I added return value handling and some more testing. With some Perl 6 magic that is NYI the syntax should be able to be simplified to something like.