Search code examples
rreference-class

R: Change the fields' (slots') values of the class assigning a value to some other field


Assgning a value to one field, how can I make the other fields changing.

Consider the following ReferenceClass object:

C<-setRefClass("C", 
      fields=list(a="numeric",b="numeric")
      , methods=list(
      seta = function(x){
      a<<-x
      b<<-x+10
      cat("The change took place!")
      }
      ) # end of the methods list
      ) # end of the class

Now create the instance of the class

c<-C$new() 

This command

c$seta(10)

will result in that c$a is 10 and c$b is 20.

So it actually works, however, I want to achieve this result by the command

c$a<-10

(i.e. after that I want c$b to be equal to 20 as defined in the class in the logic of seta() function)
How can I do it?


Solution

  • I think you are looking for accessor functions, which are described in detail in ?ReferenceClasses. This should work:

    C<-setRefClass("C", 
        fields=list(
            a=function(v) {
                  if (missing(v)) return(x)
                  assign('x',v,.self)                    
                  b<<-v+10
                  cat ('The change took place!')
                }
           ,b="numeric"
        )
        ,methods=list(
            initialize=function(...)  {
                 assign('x',numeric(),.self)
                .self$initFields(...)
            } 
        )
    )
    
    c<-C$new()
    c$a
    # numeric(0)
    c$a<-3
    # The change took place!
    c$b
    # 13
    c$a
    # 3
    

    It does have the side effect that a new value, x is now in the environment c (the class object), but it is 'hidden' from the user in the sense that just printing c will not list x as a field.