Copying R5 reference classes with a locked variable

255 Views Asked by At

I can copy an R5 reference class when I have not locked one of the fields, but it does not copy if one of the fields is locked. Example code follows (with the lock call commented out). My question: Why can't I make a copy of the instance with a locked field using the copy() method?

example <- setRefClass('example',
    fields = list(
        count = 'numeric',
        data = 'data.frame', 
        d.accessor = function(x) {
            if ( !missing(x) ) 
                data <<- x
            else
                .self$data 
        }
    ),
    methods = list(
        initialize = function( data ) {
            if (!missing( data ))
                d.accessor <<- data
            count <<- 0
        },
        finalize = function()
            print('Bye Bye'),
        accumulate = function(x)
            count <<- count + x
    )
)

#example$lock('data') # write-1, read-many
instance <- example$new() # instantiation
df <- data.frame(x=1, y=2)# example df
instance$d.accessor <- df # 1st set - okay!
copyInst <- instance$copy()
1

There are 1 best solutions below

0
On

It is because when you copy the instance, the field data will be assigned twice, which is forbidden by the lock. It will assigned first by copying instance$data value into copyInst$data, and second when copying instance$d.accessor into copyInst$d.accessor, because d.accessor is a getter/setter, and the way you defined it, assigning to it results in assigns to $data.

Illustration:

example$lock('data') # write-1, read-many
instance <- example$new() # instantiation
df <- data.frame(x=1, y=2)# example df
instance$data <- df # 1st assignement: OK
instance$d.accessor <- df #snd assignemnt: ERROR
Error: invalid replacement: reference class field ‘data’ is read-only