Albert-Jan Roskam
2010-Apr-25 13:07 UTC
[R] method dispatching vs inheritance/polymorphism (re-post)
Hi, I'm having trouble seeing the added value over functions defined by setGeneric vis-a-vis methods defined by inheritance and polymorphism. setGeneric offers a 'clean' call to a generic function, ie. no need to call new(), so less typing to do for the user. But such explicit calls can also be avoided by functions like f <- function(x, y) new(Class = SomeClass, x=x, y=y). Then again, R relies heavily on method dispatching, so it must have clear advantages. *confused* Can anybody enlighten me? Thanks in advance! Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [[alternative HTML version deleted]]
Duncan Murdoch
2010-Apr-25 13:23 UTC
[R] method dispatching vs inheritance/polymorphism (re-post)
On 25/04/2010 9:07 AM, Albert-Jan Roskam wrote:> Hi, > > I'm having trouble seeing the added value over functions defined by setGeneric vis-a-vis > methods defined by inheritance and polymorphism. setGeneric offers a 'clean' call to a generic function, ie. no need to call new(), so less typing to do for the user. But such explicit calls can also be avoided by functions like f <- function(x, y) new(Class = SomeClass, x=x, y=y). Then again, R relies heavily on method dispatching, so it must have clear advantages. > > *confused* Can anybody enlighten me? Thanks in advance!I agree you are confused. setGeneric sets up a function to use to dispatch methods on an object; e.g. the stats4 package defines the generic AIC, so that AIC(obj) will calculate the AIC for any object that provides an AIC method. new() is not involved, because the object was already created somewhere else. What you seem to be asking about is something like a constructor function. E.g. if I have a class "SomeClass", instead of new("SomeClass", x=x, y=y) I might prefer to type SomeClass(x=x, y=y). That's possible (you have to do it yourself, like your f() above), but is really unrelated to setGeneric. Duncan Murdoch