Session Ready
Exercise

Read the Rating

The data stored by an R6 object is deliberately hidden away from the user by keeping it in the private element. This is the principle of encapsulation.

If you want to provide access to any of the data values, you can use an active binding. These are functions that behave like variables.

Active bindings are stored in the active element of an R6 object. To create an active binding to get a private data field (i.e. a "read-only" binding), you create a function with no arguments that simply returns the private element.

The pattern for creating a read-only active binding is as follows:

thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value"
  ),
  active = list(
    a_field = function() {
      private$..a_field
    }
  )
)

The active binding is called like a data variable, not a function.

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

A microwave oven factory has been partially defined for you.

  • Update the definition to include a read-only active binding to get the power rating.
    • The active binding should be named power_rating_watts.
    • This is defined as a function, with no arguments.
    • The body should simply return the private ..power_rating_watts field.
  • Create a microwave oven object and assign it to a_microwave_oven.
  • Read its power rating.