Aan de slagGa gratis aan de slag

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()

Deze oefening maakt deel uit van de cursus

Object-Oriented Programming with S3 and R6 in R

Cursus bekijken

Oefeninstructies

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).

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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(___, ___)  
Code bewerken en uitvoeren