Get startedGet started for free

Learning to Cook

The third argument to R6Class() is called public and holds the user-facing functionality for the object. This argument should be a list, with names for each of its elements.

The public element of an R6 class contains the functionality available to the user. Usually it will only contain functions.

The updated pattern for creating an R6 class generator is as follows:

thing_factory <- R6Class(
  "Thing",
  private = list(
    a_field = "a value",
    another_field = 123
  ),
  public = list(
    do_something = function(x, y, z) {
      # Do something here
    }
  )
)

This exercise is part of the course

Object-Oriented Programming with S3 and R6 in R

View Course

Exercise instructions

A microwave oven factory has been partially defined for you.

  • Update the public element of the definition to include a cook method.
    • The cook method is a function.
    • It should have one argument named time_seconds to denote the cooking time.
    • In the body of the cook method, you should pass time_seconds to Sys.sleep() (docs), which does nothing for the allotted amount of time.
    • Finally, the cook method should print() (docs) the string "Your food is cooked!"
  • Create a microwave oven object called a_microwave_oven using the microwave_oven_factory's new() method.
  • Call a_microwave_oven's cook() method, for 1 second.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Add a cook method to the factory definition
microwave_oven_factory <- R6Class(
  "MicrowaveOven",
  private = list(
    power_rating_watts = 800
  ),
  public = list(
    ___ = ___(___) {
      ___
      ___
    }
  )
)

# Create microwave oven object
a_microwave_oven <- ___

# Call cook method for 1 second
___
Edit and Run Code