Search code examples
rr6

Access elements of an R6 class that instantiates another R6 class


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().


Solution

  • 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
      )
    )