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.
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
A MicrowaveOven class has been partially defined for you.
- In the private element of the
MicrowaveOvenclass, update the field namedshared.- This field should contain three lines of code wrapped in braces,
{}. - First it should call
new.env()(docs) to create a new environment namede, then … - Assign a variable into
enamedsafety_warning, that takes the value"Warning. Do not try to cook metal objects.", then … - Return the environment.
- This field should contain three lines of code wrapped in braces,
- Add an active binding named
safety_warningthat gets or sets the private sharedsafety_warningfield.- Define this as a function inside the
activeelement. - It takes a single argument named
value. - It should get or set
private$shared$safety_warning.
- Define this as a function inside the
- Create two
MicrowaveOvenobjects, nameda_microwave_ovenandanother_microwave_ovenrespectively. - Change the
safety_warningfield ona_microwave_ovento"Warning. If the food is too hot you may scald yourself.". - Look at the
safety_warningfield onanother_microwave_ovento make sure that it has been altered.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Complete the class definition
microwave_oven_factory <- R6Class(
"MicrowaveOven",
private = list(
shared = {
# Create a new environment named e
___
# Assign safety_warning into e
___
# Return e
___
}
),
active = list(
# Add the safety_warning binding
safety_warning = ___(___) {
if(___(___)) {
___
} else {
___ <- ___
}
}
)
)
# Create two microwave ovens
a_microwave_oven <- ___
another_microwave_oven <- ___
# Change the safety warning for a_microwave_oven
___ <- "Warning. If the food is too hot you may scald yourself."
# Verify that the warning has change for another_microwave
___