Attack of the Clones (2)
If an R6 object contains another R6 object in one or more of its fields, then by default clone() will copy the R6 fields by reference. To copy those R6 fields by value, the clone() method must be called with the argument deep = TRUE.
a_deep_copy <- an_r6_object$clone(deep = TRUE)
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
A PowerPlug R6 class to describe the microwave's power plug, has been predefined in your workspace. The MicrowaveOven class has been updated to include a PowerPlug object.
- Create a
MicrowaveOvenobject and assign it toa_microwave_oven. - Copy the microwave into a variable named
cloned_microwave_ovenusing theclone()method, with no arguments. - Copy the microwave into a variable named
deep_cloned_microwave_ovenusing theclone()method, passingdeep = TRUE. - Change the
typefield of thepower_plugfield ofa_microwave_ovento"British". - Verify that the
power_plug$typefields ofa_microwave_ovenandcloned_microwave_ovenare identical. - Verify that the
power_plug$typefields ofa_microwave_ovenanddeep_cloned_microwave_ovenare different.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a microwave oven
a_microwave_oven <- microwave_oven_factory$new()
# Look at its power plug
a_microwave_oven$power_plug
# Copy a_microwave_oven using clone(), no args
cloned_microwave_oven <- ___
# Copy a_microwave_oven using clone(), deep = TRUE
deep_cloned_microwave_oven <- ___
# Change a_microwave_oven's power plug type
___$___ <- ___
# Check a_microwave_oven & cloned_microwave_oven same
identical(___, ___)
# Check a_microwave_oven & deep_cloned_microwave_oven different
identical(___, ___)