1. Learn
  2. /
  3. Courses
  4. /
  5. Object-Oriented Programming with S3 and R6 in R

Connected

Exercise

This is the End (of an R6 Object)

Just as an R6 class can define a public initialize() method to run custom code when objects are created, they can also define a public finalize() method to run custom code when objects are destroyed. finalize() should take no arguments. It is typically used to close connections to databases or files, or undo side-effects such as changing global options() (docs) or graphics par() (docs) parameters.

The template for the code should be as follows.

thing_factory <- R6Class(
  "Thing",
  public = list(
    initialize = function(x, y, z) {
      # do something
    },
    finalize = function() {
      # undo something
    }
  )
)

The finalize() method is called when the object is removed from memory by R's automated garbage collector. You can force a garbage collection by typing gc() (docs).

Instructions 1/2

undefined XP
    1
    2

A MicrowaveOven class has been predefined in your workspace as microwave_oven_factory. An SQLite database containing cooking times for different food types has been created in your working directory. The RSQLite (docs) package has been loaded.

  • Complete the definition for a SmartMicrowaveOven class,
    • The class should inherit from microwave_oven_factory.
    • The private element should have a field named conn, initially set to NULL.
    • The initialize() method should connect to the SQLite database, using dbConnect(SQLite(), "cooking-times.sqlite"),
    • This connection should be stored in the private conn field.
    • The finalize() method should display a message() (docs) stating "Disconnecting from the cooking times database.", then disconnect from the database using dbDisconnect(private$conn).
  • Create a SmartMicrowaveOven object and assign it to a_smart_microwave.
  • Call the get_cooking_time() method with "soup" as the food argument.