Search code examples
rr-s4

In R how to define a method with the same name in different S4 classes for a correct method dispatching


I've defined a method called "getValues" for a new S4 class in R. My class and method are:

myClass<-setClass("MyClass", 
                  slots=list(a="numeric",b="list"))

setMethod("getValues", signature ( "MyClass", "missing", "missing"),
          getValues<-function(x)
          {
            print("MyClass-getValues called")
          })

The 'raster' package already has a method called 'getValues' but with different signatures (can be seen with showMethods("getValues")). So I thought method dispatching will select the correct method depending of the signature. But when I run:

a<-raster()
getValues(a)  #problem: this calls "getValues" of the class 'MyClass' and prints "MyClass-getValues called"

I expected that the 'getValues' method for RasterLayer objects will be called, but this calls "getValues" of the class 'MyClass'!

Where is the error?


Solution

  • The error is in the commented line below:

    myClass<-setClass("MyClass", 
                      slots=list(a="numeric",b="list"))
    
    setMethod("getValues", signature ( "MyClass", "missing", "missing"),
              ##getValues<-function(x)##
              {
                print("MyClass-getValues called")
              })
    

    This line overwrites the main definition of getValues as well as setting a method. Call this function anything other than getValues and it should work.