R6Class creates the R6 reference object$clone() method to copy the object|> syntaxself invisibly.$print() modifies the default printing method#> Pretty Accumulator Object
#> Current sum: 4
$initialize() overides the default behaviour of $new()#> Person
#> name: Nick
#> Error in initialize(...): is.character(name) is not TRUE
$set() assigns methods after creating R6 objectsNote
Keep in mind methods added with $set() are only available with new objects.
Transaction <- R6Class("Transaction",
public = list(
last_transaction = 0,
initialize = function(owner) {
private$owner <- owner
invisible(self)
},
deposit = function(amount) {
private$balance <- private$balance + amount
self$last_transaction <- amount
invisible(self)
},
withdraw = function(amount) {
private$balance <- private$balance - amount
self$last_transaction <- -amount
invisible(self)
},
print = function(...) {
cat("Transactions by ",private$owner,"\n")
cat(" Last transaction: ",self$last_transaction,"\n")
cat(" Balance: ",private$balance,"\n")
}
),
private = list(
owner = NULL,
balance = 0
)
)
t <- Transaction$new("Nick")
t$owner#> NULL
$print() can reveal private fieldsPerson <- R6Class("Person",
private = list(
.age = NA,
.name = NULL
),
active = list(
age = function(value) {
if (missing(value)) {
private$.age
} else {
stop("`$age` is read only", call. = FALSE)
}
},
name = function(value) {
if (missing(value)) {
private$.name
} else {
stopifnot(is.character(value), length(value) == 1)
private$.name <- value
self
}
}
),
public = list(
initialize = function(name, age = NA) {
private$.name <- name
private$.age <- age
}
)
)
nick <- Person$new("Nick", age = 33)
nick$name#> [1] "Nick"
#> Error in (function (value) : is.character(value) is not TRUE
#> Error: `$age` is read only
inherit allows providing behavior from existing R6 classessuper$add() is the add method call from the inherited object$finalize() deletes/unlinks anything created by the R6 object#> [1] "Finalizer has been called!"
#> used (Mb) gc trigger (Mb) max used (Mb)
#> Ncells 622966 33.3 1375035 73.5 1375035 73.5
#> Vcells 1162108 8.9 8388608 64.0 2090411 16.0