Search code examples
rreference-class

setRefClass pass by value, pass by reference


I suspect i am not understanding all the aspects of setRefClass in R. Lets say I have an instance of a setRefClass initialized. I want to create the variable X so that this variable is equal to a copy of the instance or refers to the instance of setRefClass. Is there a difference between:

x = InstanceOfsetRefClass

and

x <<- InstanceOfsetRefClass

I don't fully understand and it seems I have strange behavior in my code.

Thanks for your help


Solution

  • I don't think your problem is anything to do with reference classes, rather it's about scope. Consider the following example. We start by removing all variables from our workspace and create a definition for A:

    rm(list=ls())
    A = setRefClass("A", fields=list(x="numeric"))
    

    Next we create and call the function f:

    f = function() {
      x1 = 1
      a1 = A$new(x=10)
      x2 <<- 2
      a2 <<- A$new(x=10)
    }
    f()
    

    The key difference between <<- and = is

    The operators '<<-' and '->>' are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment.

    From the help page: ?"<<-"

    So variables created using = aren't found in the global enviroment

    R> x1
    Error: object 'x1' not found
    R> a1
    Error: object 'a1' not found
    

    but the other variables are:

    R> x2
    [1] 2
    R> a2
    Reference class object of class "A"
    Field "x":
    [1] 10