Close the Door
Methods for an R6 object can access its private fields by using the private$
prefix.
thing_factory <- R6Class(
"Thing",
private = list(
a_field = "a value",
another_field = 123
),
public = list(
do_something = function(x, y, z) {
# Access the private fields
paste(
private$a_field,
private$another_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. It has been updated to include a private door_is_open
field, and a public open_door
method.
- Add a public method named
close_door()
to close the microwave door.- The method should take no arguments.
- In the body of the function, set the
door_is_open
field toFALSE
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add a close_door() method
microwave_oven_factory <- R6Class(
"MicrowaveOven",
private = list(
power_rating_watts = 800,
door_is_open = FALSE
),
public = list(
cook = function(time_seconds) {
Sys.sleep(time_seconds)
print("Your food is cooked!")
},
open_door = function() {
private$door_is_open <- TRUE
},
___ = ___
)
)