Search code examples
roopreference-class

R reference classes as a field of a reference class


I would like to pass a reference class to a reference class constructor, and assign the passed reference class as a field. However, when I run the code below, I don't understand why I get an error. My questions are:

1) Please can someone kindly explain why this error is occurring:

> a <- ClassA&new()
Error in .getClassFromCache(Class, where) : 
  argument "Class" is missing, with no default
> b <- ClassB$new(a)
Error in .Object$initialize(...) : object 'a' not found

2) I have declared class.a.container as class "list", however I want this to be a reference class. What do I need to put here instead of "list" ?

ClassA <- setRefClass(
  "ClassA",

  fields = list(myVar = "numeric"),

  methods = list(
    someMethod = function(){
      print("hi")
    }
  )
)

ClassB <- setRefClass(
  "ClassB",

  fields = list(class.a.container = "list"),

  methods = list(
    initialize = function(class.a){
      class.a.container <<- class.a
  })
)

a <- ClassA&new()
b <- ClassB$new(a)

Solution

  • Y'er gonna feel kind of silly, at least I did when I noticed the problem. You have an ampersand insead of a dollar-sign in the extraction from the envirnment-class-item.

    a <- ClassA$new(myVar=1)
    a$someMethod(2)
    #[1] "hi