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
MicrowaveOven
object and assign it toa_microwave_oven
. - Copy the microwave into a variable named
cloned_microwave_oven
using theclone()
method, with no arguments. - Copy the microwave into a variable named
deep_cloned_microwave_oven
using theclone()
method, passingdeep = TRUE
. - Change the
type
field of thepower_plug
field ofa_microwave_oven
to"British"
. - Verify that the
power_plug$type
fields ofa_microwave_oven
andcloned_microwave_oven
are identical. - Verify that the
power_plug$type
fields ofa_microwave_oven
anddeep_cloned_microwave_oven
are 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(___, ___)