Skip to content
Prev 317605 / 398506 Next

2 setGeneric's, same name, different method signatures

On 2/14/2013 8:57 AM, Greg Minshall wrote:
Hi Greg --

this setGeneric is over-writing the first, as would

f = function() "first"
f = function() "second"
f() # "second"

If you'd like to dispatch on a single argument, then

setGeneric("one", function(x, ...) standardGeneric("one"))
setMethod("one", "A", function(x, ...) "A-method")
setMetohd("one", "B", function(x, y, ...) "B-method")

The '...' in the generic allow you to add arguments that are 'picked off' by 
methods. The user could provide any value for y, not only an object of class "B".

If you'd like to dispatch sometimes on two arguments then

setGeneric("two", function(x, y, ...) standardGeneric("two"))
setMethod("two", c("A", "ANY"), function(x, y, ...) "A,ANY-method")
setMethod("two", c("B", "B"), function(x, y, ...) "B,B-method")

then two(new("A")), two(new("A"), new("A")) and two(new("A"), new("B")) end up 
in A,ANY,two-method while two(new("B"), new("B")) ends up in "B,B,two-method". 
Other combinations are errors. One might instead not define A,ANY but instead

setMethod("two", c("A", "missing"), function(x, y, ...) "A,missing-method")

and then two(new("A"), new("A")) would be an error.

Multiple dispatch is complicated, and perhaps best to avoid if possible.

It's possible to write a generic and methods that dispatch on '...', with the 
requirement that all classes are the same; this in the spirit of comparing two 
B's and returning the smaller; see ?dotsMethods though again this is not a 
trivial use case.

Hope that helps enough.

Martin