user2623214
user2623214

Reputation: 153

Dispatching s4 method on an s3 object

I recently defined an s4 method for an s3 class by mistake. For example:

> foo <- structure(list(a=1),class='Bar')

And then define an s4 method like this

> setMethod('show','Bar',function(object) cat('-->',object$a,'\n'))
in method for 'show' with signature '"Bar"': no definition for class "Bar"

You get a warning, but otherwise things seem okay. And then

> show(foo)
--> 1 

has the intended behavior. Why does this work?

Upvotes: 1

Views: 76

Answers (1)

IRTFM
IRTFM

Reputation: 263352

"Why"-questions can be difficult to answer with authority because most of the designers of the language will not see this question. If it were posted on the R-devel Mailing List it might have a chance of being addressed with the needed authority. My take on it is that R and S before it were primarily functionally focussed so calling an object "S4" isn't really what was intended. It's the methods (functions) that were intended to be called S3 or S4, and S4 methods were intended to work with named classes, and so should succeed with object that have classes which were originally intended to be used with S3 methods. In other words there was never an intent to have a sharp dividing line between classes defined by whether they were originally being created or used by S3 methods.

A slightly more trivial/flippant answer has also occurred to me as well. If the code you used had thrown an error, then the help page for setMethod would also have thrown an error and the methods-package would not have compiled and the would be no current version of R. That because the same sort of code appears as the first executable line in that help page and it throws the same warning.

You are warned in the ?setMethods page that:

Old-style (‘S3’) classes can also be used, if you need compatibility with these, but you should definitely declare these classes by calling setOldClass if you want S3-style inheritance to work.

Upvotes: 2

Related Questions