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()
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
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.
- The active binding should be named
- Create a microwave oven object and assign it to
a_microwave_oven
. - Read its power rating.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add a binding for power rating
microwave_oven_factory <- R6Class(
"MicrowaveOven",
private = list(
..power_rating_watts = 800
),
active = list(
# Add the binding here
___ = ___
)
)
# Make a microwave
a_microwave_oven <- ___
# Get the power rating
___