Access elements of an R6 class that instantiates another R6 class

597 Views Asked by At

Say I have a class SimpleClass and one of the methods of that class can return an object of another class, e.g.

SimpleClass <- R6::R6Class(
  "SimpleClass",
  public = list(
    initialize = function() {
      private$a <- 1
    },
    cls_two = function() SimpleClass2$new()
  ),
  private = list(
    a = numeric()
  )
)

Where SimpleClass2 is

SimpleClass2 <- R6::R6Class(
  "SimpleClass2",
  public = list(
    initialize = function() {
      private$b <- 2
    },
    get_a = function() private$a
  ),
  private = list(
    b = numeric()
  )
)

Here, if I were instantiate SimpleClass and call the method cls_two(), the resulting object will not have access to the elements of the first object unless I pass them on. Is there a way for the secondary class to access elements of the first class?

first <- SimpleClass$new()
second <- first$cls_two()
second$get_a()
# NULL

Note that I do not want to use inheritance in the traditional sense because I do not want to reinstantiate the first class. I would also prefer not to have to pass on all of the objects to SimpleClass2$new().

2

There are 2 best solutions below

7
On BEST ANSWER

Extend SimpleClass2’s constructor to take an object of type SimpleClass, and pass self when calling the constructor in SimpleClass::cls_two:

SimpleClass2 <- R6::R6Class(
  "SimpleClass2",
  public = list(
    initialize = function(obj) {
      private$b <- 2
      private$obj <- obj
    },
    get_a = function() private$obj
  ),
  private = list(
    b = numeric(),
    obj = NULL
  )
)
0
On

You can make SimpleClass2 have a member that is a Simpleclass and have an option to pass a simpleclass in its constructor:

SimpleClass <- R6::R6Class(
  "SimpleClass",
  public = list(
    initialize = function() {
      private$a <- 1
    },
    cls_two = function() SimpleClass2$new(self)
  ),
  private = list(
    a = numeric()
  )
)

SimpleClass2 <- R6::R6Class(
  "SimpleClass2",
  public = list(
    initialize = function(Simp1 = SimpleClass$new()) {
      private$a <- Simp1
      private$b <- 2
    },
    get_a = function() private$a
  ),
  private = list(
    a = SimpleClass$new(),
    b = numeric()
  )
)

Which works like this:

first <- SimpleClass$new()
second <- first$cls_two()
second$get_a()
#> <SimpleClass>
#>   Public:
#>     clone: function (deep = FALSE) 
#>     cls_two: function () 
#>     initialize: function () 
#>   Private:
#>     a: 1