r-lib / R6

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

Deep copy of R6 classes with inheritance #72

Closed kablag closed 9 years ago

kablag commented 9 years ago

Maybe this is very strange class usage, but it does not work after object cloning.

baseClass <- R6Class("baseClass", public = list( initialize = function() {}, ShowVal = function() { private$.val }), private = list( .val = 1, deep_clone = function(name, value) { if (value %>% class %>% tail(1) != "R6") { value } else { value$clone(deep = TRUE) } } ), active = list( Val = function() { private$.val } ) )

subClass <- R6Class("subClass", inherit = baseClass, public = list( ShowVal = function() { super$ShowVal() + private$.b$ShowVal() } ), private = list( .b = baseClass$new() ))

sub <- subClass$new() sub2 <- sub$clone(deep = TRUE) sub$ShowVal() sub2$ShowVal()

wch commented 9 years ago

Simplified example:

library(R6)
baseClass <- R6Class("baseClass",
  public = list(
    ShowVal = function() private$val
  ),
  private = list(
    val = 1
  )
)

subClass <- R6Class("subClass",
  inherit = baseClass,
  public = list(
    ShowVal = function() super$ShowVal()
  )
)

sub <- subClass$new()
sub2 <- sub$clone()
sub$ShowVal()
# [1] 1
sub2$ShowVal()
# Error in super$ShowVal() : object 'private' not found

It looks like, for cloned objects, the super functions aren't getting private in their enclosing environment:

ls(environment(sub$`.__enclos_env__`$super$ShowVal))
# [1] "private" "self"   

ls(environment(sub2$`.__enclos_env__`$super$ShowVal))
# [1] "self"