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
MicrowaveOvenobject and assign it toa_microwave_oven. - Copy the microwave into a variable named
assigned_microwave_ovenusing<-assignment. - Copy the microwave into a variable named
cloned_microwave_ovenusinga_microwave_oven'sclone()method. - Change the
power_level_wattsfield ofa_microwave_ovento400. - Verify that the
power_level_wattsfields ofa_microwave_ovenandassigned_microwave_ovenareidentical()(docs). - Verify that the
power_level_wattsfields ofa_microwave_ovenandcloned_microwave_ovenare 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(___, ___)