Get startedGet started for free

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

View Course

Exercise instructions

A microwave oven factory has been predefined in your workspace as microwave_oven_factory.

  • Create a MicrowaveOven object and assign it to a_microwave_oven.
  • Copy the microwave into a variable named assigned_microwave_oven using <- assignment.
  • Copy the microwave into a variable named cloned_microwave_oven using a_microwave_oven's clone() method.
  • Change the power_level_watts field of a_microwave_oven to 400.
  • Verify that the power_level_watts fields of a_microwave_oven and assigned_microwave_oven are identical() (docs).
  • Verify that the power_level_watts fields of a_microwave_oven and cloned_microwave_oven are not identical() (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(___, ___)  
Edit and Run Code