Get startedGet started for free

Cloning R6 Objects

1. Cloning R6 Objects

As you saw earlier in the chapter,

2. Environments use copy by reference

environments have special copy by reference behavior. Since R6 objects are built using environments, they also use copy by reference. To see how it works,

3. thing_factory

let's use a template Thing class with a private field containing a single number, and an active binding. The active binding simply allows getting and setting of the field, with no extra logic.

4. a_thing

If you create an object, then use assignment to copy it, changing a field in one object changes it for all objects. Sometimes that isn't the behavior that you want, so all R6 objects have a method named

5. clone() copies by value

clone to allow independent copies. You don't need to define this method yourself; it will be automatically generated. To copy the object using the more standard copy by value behavior,

6. a_clone

just call the clone method without any arguments. Now when you change one of the fields in the original, the clone is unaffected. One special case is when R6 classes contain other R6 classes.

7. container_factory

Here's an example of a Container class that contains a private Thing object. The dot dot thing field is created with the thing_factory's new method, and there is an active binding to access it. If you clone the container,

8. a_container

then changes in the Thing object that it contains are also reflected in the Thing object of the clone. To use copy by value for the fields of the internal R6 object,

9. a_deep_clone

you need to call clone with the argument deep equals TRUE. This time, the changes to thing dollar a_field aren't propagated along to the deep copy.

10. Summary

To summarize, just like environments, R6 objects use copy by reference behavior. To override this and copy them by value instead, you call their clone method. clone is automatically generated for you; you don't have to define it yourself. If your R6 object contains other R6 objects, you have to pass the argument deep equals TRUE to provide copy by value behavior for those fields.

11. Let's practice!