Get startedGet started for free

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

This exercise is part of the course

Object-Oriented Programming with S3 and R6 in R

View Course

Hands-on interactive exercise

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

# Microwave_factory is predefined
microwave_oven_factory

# Complete the class definition
smart_microwave_oven_factory <- R6Class(
  "SmartMicrowaveOven",
  inherit = ___, # Specify inheritance
  private = list(
    # Add a field to store connection
    ___ = ___
  ),
  public = list(
    initialize = function() {
      # Connect to the database
      ___$___ = ___(___(), "___")
    },
    get_cooking_time = function(food) {
      dbGetQuery(
        private$conn,
        sprintf("SELECT time_seconds FROM cooking_times WHERE food = '%s'", food)
      )
    },
    finalize = function() {
      # Print a message
      ___("___")
      # Disconnect from the database
      ___(___$___)
    }
  )
)

# Create a smart microwave object
a_smart_microwave <- ___
  
# Call the get_cooking_time() method
___
Edit and Run Code