r-lib / R6

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

Inherited methods in clone of non-portable object have incorrect environment #214

Closed wch closed 3 years ago

wch commented 3 years ago

When a non-portable object with inheritance is cloned, methods that are inherited (and not overridden) do not get the new object's environment. Originally from #212.

library(R6)
A <- R6Class("A",
  portable = F,
  public = list(
    getx = function() x,
    getx2 = function() x,
    x = 1
  )
)

B <- R6Class("B",
  portable = F,
  inherit = A,  
  public = list(
    # Override getx2, but not getx
    getx2 = function() x
  )
)

b <- B$new()
bc <- b$clone()
b$x <- 10

# Both of these return 10, which is correct
b$getx()
#> [1] 10
b$getx2()
#> [1] 10

# Returns 10, which is incorrect!
bc$getx()
#> [1] 10
# Returns 1, which is correct
bc$getx2()
#> [1] 1