Session Ready
Exercise

Static Electricity

R6 classes can use environments' copy by reference behavior to share fields between objects. To set this up, define a private field named shared. This field takes several lines to define. It should:

  • Create a new environment.
  • Assign any shared fields to that environment.
  • Return the environment.

The shared fields should be accessed via active bindings. These work in the same way as other active bindings that you have seen, but retrieve the fields using a private$shared$ prefix.

R6Class(
  "Thing",
  private = list(
    shared = {
      e <- new.env()
      e$a_shared_field <- 123
      e
    }
  ),
  active = list(
    a_shared_field = function(value) {
      if(missing(value)) {
        private$shared$a_shared_field
      } else {
        private$shared$a_shared_field <- value
      }
    }
  )
)

Note that the name of the active binding must be the same as the name of the shared field that you want to get or set; they are both a_shared_field in the above example.

Instructions
100 XP

A MicrowaveOven class has been partially defined for you.

  • In the private element of the MicrowaveOven class, update the field named shared.
    • This field should contain three lines of code wrapped in braces, {}.
    • First it should call new.env() to create a new environment named e, then ...
    • Assign a variable into e named safety_warning, that takes the value "Warning. Do not try to cook metal objects.", then ...
    • Return the environment.
  • Add an active binding named safety_warning that gets or sets the private shared safety_warning field.
    • Define this as a function inside the active element.
    • It takes a single argument named value.
    • It should get or set private$shared$safety_warning.
  • Create two MicrowaveOven objects, named a_microwave_oven and another_microwave_oven respectively.
  • Change the safety_warning field on a_microwave_oven to "Warning. If the food is too hot you may scald yourself.".
  • Look at the safety_warning field on another_microwave_oven to make sure that it has been altered.