develooper Front page | perl.perl6.language | Postings from August 2001

Re: CLOS multiple dispatch

Thread Previous | Thread Next
Damian Conway
August 29, 2001 23:16
Re: CLOS multiple dispatch
Message ID:
Schwern explained:

   >     # Following RFC 256
   >     sub name (Foo $self) : multi {
   >         return $self->{name};
   >     }
   >     sub name (Foo $self, STRING $name) : multi {
   >         $self->{name} = $name;
   >         return $self->{name};
   >     }
   > which is quite a bit simpler.

...and more efficient (since the selection is done in the core dispatcher,
not in the subroutine itself).

However, there is much more to multiple dispatch than this (technically,
Schwern's example is just subroutine overloading).

For example, here is an event handler for a GUI:

	sub handle (Window $w, Event $e) : multi {
		log("Unknown event $($e->desc) called on window $($w->name)");

	sub handle (Window $w, CloseEvent $e) : multi {

	sub handle (ImportantWindow $w, CloseEvent $e) : multi {
		$w->close if yesno_dialog("Really close this window???");

	sub handle (Window $w, MoveEvent $e) : multi {

	sub handle (FixedWindow $w, MoveEvent $e) : multi {

Note that the handler that is selected depends on the *combination* of
the types of the two arguments. And that the dispatcher understands
the argument/parameter inheritance relationships and selects the most
specific handler for each combination. For example, a MoveEvent sent to
a FixedWindow causes a beep, but a MoveEvent sent to any other type of
window is dispatched to the more-generic handle(Window $w, MoveEvent $e)
subroutine, which causes it to move.


Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About