Get startedGet started for free

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

View Course

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 to a_microwave_oven.
  • Copy the microwave into a variable named cloned_microwave_oven using the clone() method, with no arguments.
  • Copy the microwave into a variable named deep_cloned_microwave_oven using the clone() method, passing deep = TRUE.
  • Change the type field of the power_plug field of a_microwave_oven to "British".
  • Verify that the power_plug$type fields of a_microwave_oven and cloned_microwave_oven are identical.
  • Verify that the power_plug$type fields of a_microwave_oven and deep_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(___, ___)  
Edit and Run Code