First Thing's First
There is one special public method named initialize()
(note the American English spelling). This is not called directly by the user. Instead, it is called automatically when an object is created; that is, when the user calls new()
.
initialize()
lets you set the values of the private fields when you create an R6 object. The pattern for an initialize()
function is as follows:
thing_factory <- R6Class(
"Thing",
private = list(
a_field = "a value",
another_field = 123
),
public = list(
initialize = function(a_field, another_field) {
if(!missing(a_field)) {
private$a_field <- a_field
}
if(!missing(another_field)) {
private$another_field <- another_field
}
}
)
)
Notice the use of missing()
(docs). This returns TRUE
if an argument wasn't passed in the function call.
Arguments to the factory's new()
method are passed to initialize()
.
a_thing <- thing_factory$new(
a_field = "a different value",
another_field = 456
)
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.
- Add a public method named
initialize()
. This should allow the user to set thepower_rating_watts
anddoor_is_open
fields when the object is created.- The arguments should be
power_rating_watts
anddoor_is_open
. - In the body of the
initialize()
method, for each argument, if it is notmissing()
(docs), then the corresponding private field should be set.
- The arguments should be
- Create a microwave object with a power rating of
650
watts, and an open door.- Call
microwave_oven_factory
'snew()
method. - Pass the arguments
power_rating_watts = 650
anddoor_is_open = TRUE
tonew()
. - Assign the result to
a_microwave_oven
.
- Call
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add an initialize 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
},
close_door = function() {
private$door_is_open <- FALSE
},
# Add initialize() method here
___ = ___(___, ___) {
if(!missing(power_rating_watts)) {
private$power_rating_watts <- power_rating_watts
}
___
}
)
)
# Make a microwave
a_microwave_oven <- ___