Session Ready
Exercise

Control the Power

Active bindings can also be used to set private fields. In this case, the binding function should accept a single argument, named "value".

The pattern for creating a read/write active binding is as follows.

thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value"
  ),
  active = list(
    a_field = function(value) {
      if(missing(value)) {
        private$..a_field
      } else {
        assert_is_a_string(value) # or another assertion
        private$..a_field <- value
      }
    }
  )
)

Values are assigned as though the binding was a data variable, not a function.

a_thing <- thing_factory$new()
a_thing$a_field <- "a new value" # not a_thing$a_field("a new value")
Instructions
100 XP

A microwave oven class has been partially defined for you.

  • Extend the definition of the microwave oven class to include an active list element.
  • Add an active binding to the active element control the power level.
    • The function should be called power_level_watts.
    • It should accept a single argument named value.
    • The private variable to get/set is called ..power_level_watts.
    • Use assert_is_a_number() to check that value is a single number.
    • Use assert_all_are_in_closed_range() to check that value is between 0 and ..power_rating_watts.
  • Create a microwave oven object, and assign it to a_microwave_oven.
  • Get the power level.
  • Try to set the the power level to the value "400", as a string.
  • Try to set the power level to 1600.
  • Set the power level to 400.