qed
qed

Reputation: 23104

Function overloading with reference classes in R?

Here is my attempt:

MyClass = setRefClass("MyClass", fields = c("x", "y"))
MyClass$methods(
    myadd = function() {
        x + y
    }
)
MyClass$methods(
    myadd = function(n) {
        x + y + n
    }
)
MyClass$methods(
    initialize = function(xinit, yinit) {
        x <<- xinit
        y <<- yinit
    }
)

myobj = MyClass(2, 3)
myobj$myadd()

It failed miserably of course:

Error in myobj$myadd() (from #3) : argument "n" is missing, with no default

Upvotes: 3

Views: 442

Answers (1)

cbare
cbare

Reputation: 12468

I believe the R-ish way to do that is with a default parameter to your method. Something like:

MyClass = setRefClass("MyClass", fields = c("x", "y"))
MyClass$methods(
  myadd = function(n=0) {
      x + y + n
  }
)
MyClass$methods(
  initialize = function(xinit, yinit) {
      x <<- xinit
      y <<- yinit
  }
)

Now, you'll get what I think you expect:

myobj = MyClass(2, 3)
myobj$myadd()
[1] 5

myobj$myadd(5)
[1] 10

At risk of being called a "Hadley Wickham fanboy" (again!), a great source of info about the R object system is the OO section of Hadley's Advanced R.

For what it's worth, if you do need to implement methods with complicated dispatching, the S4 object system offers quite a bit of power, but perhaps at the cost of some additional complexity and verbosity.

Upvotes: 3

Related Questions