14.3 Constructing an R6 class, the basics
- Really simple to do, just use the
R6::R6Class()
function.
Accumulator <- R6Class("Accumulator", list(
sum = 0,
add = function(x = 1) {
self$sum <- self$sum + x
invisible(self)
}
))
- Two important arguments:
classname
- A string used to name the class (not needed but suggested)public
- A list of methods (functions) and fields (anything else)
- Suggested style conventions to follow:
- Class name should follow
UpperCamelCase
. - Methods and fields should use
snake_case
. - Always assign the result of a
R6Class()
into a variable with the same name as the class.
- Class name should follow
- You can use
self$
to access methods and fields of the current object.