Reputation: 3764
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()
.
Upvotes: 2
Views: 741
Reputation: 545628
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
)
)
Upvotes: 2
Reputation: 173898
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
Upvotes: 2