14.21 Better sense of what’s going on by looking at a finalizer

  • Since R6 objects are not copied-on-modified, so they are only deleted once.
  • We can use this characteristic to complement our $initialize() with a $finalize() method.
    • i.e., to clean up after we delete an R6 object.
    • This could be a way to close a database connection.
TemporaryFile <- R6Class("TemporaryFile", list(
  path = NULL,
  initialize = function() {
    self$path <- tempfile()
  },
  finalize = function() {
    message("Cleaning up ", self$path)
    unlink(self$path)
  }
))
tf <- TemporaryFile$new()
# The finalizer will clean up, once the R6 object is deleted.
rm(tf)