Attack of the Clones (1)
R6 objects use the same copy by reference behavior as environments. That is, if you copy an R6 object using <-
assignment, then changes in one object will be reflected in the copies as well.
a_reference_copy <- an_r6_object
R6 objects have an automatically generated clone()
method that is used to create a copy by value, so that changes to one copy do not affect the others.
a_value <- an_r6_object$clone()
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
A microwave oven factory has been predefined in your workspace as microwave_oven_factory
.
- Create a
MicrowaveOven
object and assign it toa_microwave_oven
. - Copy the microwave into a variable named
assigned_microwave_oven
using<-
assignment. - Copy the microwave into a variable named
cloned_microwave_oven
usinga_microwave_oven
'sclone()
method. - Change the
power_level_watts
field ofa_microwave_oven
to400
. - Verify that the
power_level_watts
fields ofa_microwave_oven
andassigned_microwave_oven
areidentical()
(docs). - Verify that the
power_level_watts
fields ofa_microwave_oven
andcloned_microwave_oven
are notidentical()
(docs).
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()
# Copy a_microwave_oven using <-
assigned_microwave_oven <- ___
# Copy a_microwave_oven using clone()
cloned_microwave_oven <- ___$___()
# Change a_microwave_oven's power level
___ <- ___
# Check a_microwave_oven & assigned_microwave_oven same
identical(___, ___)
# Check a_microwave_oven & cloned_microwave_oven different
identical(___, ___)