R reference classes as a field of a reference class

爷,独闯天下 提交于 2019-12-04 20:10:28

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!