Respond to an unknown method call

From Rosetta Code
Revision as of 22:51, 3 June 2009 by rosettacode>Dkf (Defined new task on object method dispatch, and added a Tcl implementation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Respond to an unknown method call
You are encouraged to solve this task according to the task description, using any language you may know.

Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.

This task is intended only for object systems that use a dynamic dispatch mechanism.

Tcl

Works with: Tcl version 8.6

<lang tcl># First create a simple, conventional class and object oo::class create Example {

   method foo {} {
       puts "this is foo"
   }
   method bar {} {
       puts "this is bar"
   }

} Example create example

  1. Modify the object to have a custom ‘unknown method’ interceptor

oo::objdefine example {

   method unknown {name args} {
       puts "tried to handle unknown method \"$name\""
       if {[llength $args]} {
           puts "it had arguments: $args"
       }
   }

}

  1. Show off what we can now do...

example foo; # prints “this is foo” example bar; # prints “this is bar” example grill; # prints “tried to handle unknown method "grill"” example ding dong; # prints “tried to handle unknown method "ding"”

                  # prints “it had arguments: dong”</lang>