R reference classes as a field of a reference class
Asked Answered
L

2

1

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)
Louannlouanna answered 31/10, 2012 at 19:14 Comment(2)
I do not see any 'fields' argument in the ClassA definition. Does it make any sense to define a class with nothing in it? I'm just asking.Truman
not in real life, this is just an example. I've edited the code for clarityLouannlouanna
T
5

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
Truman answered 31/10, 2012 at 21:47 Comment(0)
A
1

42- has already pointed out one error in your code (& instead of $).

To fully answer your original question, I just want to explicitly point out that after correcting that bug, you then need to change the declaration of the field in ClassB from

class.a.container = "list"

to

class.a.container = "ClassA"

Here is complete code that works for me:

ClassA = setRefClass(
    Class = "ClassA",

    fields = list(myVar = "numeric"),

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

ClassB = setRefClass(
    Class = "ClassB",

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

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

a = ClassA$new(myVar = 1)
a

b = ClassB$new(a)
b

It prints:

...
> a
Reference class object of class "ClassA"
Field "myVar":
[1] 1
> 
> b = ClassB$new(a)
> b
Reference class object of class "ClassB"
Field "class.a.container":
Reference class object of class "ClassA"
Field "myVar":
[1] 1
Approximal answered 1/12, 2016 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.