LoslegenKostenlos loslegen

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
    }
  )
)

Diese Übung ist Teil des Kurses

Object-Oriented Programming with S3 and R6 in R

Kurs anzeigen

Anleitung zur Übung

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.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# 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
___
Code bearbeiten und ausführen