r-lib / R6

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

Fix env for cloned portable classes with inheritance #218

Closed wch closed 3 years ago

wch commented 3 years ago

When a portable object with an inherited method is cloned, the cloned object's method did not have the correct environment. This was introduced by #215, and it was the cause of https://github.com/mlr-org/mlr3/issues/568.

In this example, b2$getx() should return 1, but it returns 2:

library(R6)
A <- local({
  x <- 1
  R6Class("A",
    public = list(
      getx = function() x
    )
  )
})

B <- local({
  x <- 2
  R6Class("B",
    inherit = A,
    public = list(
      getx_super = function() super$getx()
    )
  )
})

b <- B$new()
# Inherited method
b$getx()
#> [1] 1
# Method which calls super
b$getx_super()
#> [1] 1

b2 <- b$clone()
b2$getx()
#> [1] 2
b2$getx_super()
#> [1] 2

This PR fixes the issue.