Inconsistency of S4 dispatch behavior for R6 classes

社会主义新天地 提交于 2019-12-05 16:11:52

Courtesy of Hadley Wickham I found out that setOldClass() in fact solves the problem when including the inheritance structure:

require("R6")
setOldClass(c("TestR6", "R6"))
TestR6 <- R6Class("TestR6", public = list(.x = "numeric"))
setGeneric("foo", signature = "x",
  def = function(x) standardGeneric("foo")
)
setMethod("foo", c(x = "R6"),
  definition = function(x) {
    "I'm the method for `R6`"
  })
try(foo(x = TestR6$new()))

However, AFAICT, this implies that for your packages, you need to make sure that setOldClass() is called in that way for all of your R6 classes for which you would like your S4 methods to work.

This could be done by bundling these calls in function .onLoad() or .onAttach() (see here):

.onLoad <- function(libname, pkgname) {
  setOldClass(c("TestR6_1", "R6"))
  setOldClass(c("TestR6_2", "R6"))
  setOldClass(c("TestR6_3", "R6"))
}

This is supposing that you have defined three R6 classes (TestR6_1 through TestR6_3)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!