r-lib / R6

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

shadowing a regular binding with an active binding #172

Open romainfrancois opened 5 years ago

romainfrancois commented 5 years ago
library(R6)

A <- R6Class("A", 
  public = list(
    foo = 3L
  )
)

B <- R6Class("B", inherit = A, 
  active = list(
    foo = function() 91
  )
)

b <- B$new()
#> Error in makeActiveBinding(name, active[[name]], public_bind_env): symbol already has a regular binding

Can we do one of these here:

https://github.com/r-lib/R6/blob/master/R/new.R#L121

wch commented 5 years ago

This looks related to #166 and #168. I think that for subclasses there should be better checks that ensure that public/private/active items are not overridden by items from another category. This would be the second solution you proposed.

Allowing a field to be overridden by an active binding could result in tricky problems. For example, if x is an active binding, in a method you can access super$x. However, if x is a regular (public) field, there is no super$x, only self$x.

library(R6)

A <- R6Class("A",
  public = list(
    x = 1
  ),
  active = list(
    y = function() 1
  )
)

B <- R6Class("B", inherit = A,
  public = list(
    get_self_x  = function() self$x,
    get_super_x = function() super$x
  ),
  active = list(
    y = function() super$y + 1
  )
)

b <- B$new()
b$get_self_x()
#> [1] 1
b$get_super_x()
#> NULL
b$y
#> [1] 2