r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
412 stars 57 forks source link

S4 generics - ops support #44

Closed imanuelcostigan closed 9 years ago

imanuelcostigan commented 9 years ago

Here's a simple R6 class and a method for the + op that I've added to an empty R package:

Aclass <- R6::R6Class("A", public = list(x = NA, initialize=function(x) x))

setMethod (
  f = "+",
  signature = signature(e1 = "Aclass", e2 = "numeric"),
  definition = function (e1, e2)
  {
    Aclass$new(e1$x + e2)
  }
)

Here's what I get when I devtools::load_all():

in method for ‘+’ with signature ‘e1="Aclass",e2="numeric"’: no definition for class “Aclass”

Do R6 classes not register as classes in a way that can be picked up by the S4 dispatch system? S3 method works fine.

imanuelcostigan commented 9 years ago

Do these require S4 classes? If I use a good old reference classes instead of the R6 class above, I wasn't getting an error.

wch commented 9 years ago

R6 avoids S4. Reference classes, on the other hand, do use S4 (and that's part of the reason they're slow).

It may be possible to wrap an R6 class in something to make it work well with S4, but I don't know for sure.

If you're interested in using S3 for operators, you may want to read this: https://github.com/wch/s3ops

imanuelcostigan commented 9 years ago

S3 operators work fine per the tip at wch/s3ops.Thanks

imanuelcostigan commented 9 years ago

Reopening because S4 ops not addressed. Looks like S3 ops work well enough.

wch commented 9 years ago

@imanuelcostigan Just to be clear, unless there's a really lightweight, simple way to address the issue, I'm unlikely to make any significant changes to R6 to support S4. This is because one of the original reasons for creating R6 in the first place was to avoid the overhead of S4.

imanuelcostigan commented 9 years ago

Thanks for the clarification @wch

cdeterman commented 6 years ago

The S3 operators shown in wch/s3ops works for Arith methods but how would you approach the %*% method? It doesn't appear to work the same was as + for example.

@wch do you know if it is possible to write an S3 for the %*% operator?