# A simple class
AnimalHerd <- R6Class("AnimalHerd",
public = list(
animal = "buffalo",
count = 2,
view = function() {
paste(rep(animal, count), collapse = "")
},
reproduce = function(mult = 2) {
count <<- count * mult
invisible(self)
}
)
)
herd <- AnimalHerd$new()
herd$view()
# "buffalo buffalo"
herd$reproduce()
herd$view()
# "buffalo buffalo buffalo buffalo"
# Methods that return self are chainable
herd$reproduce()$view()
"buffalo buffalo buffalo buffalo buffalo buffalo buffalo buffalo"
# An example that demonstrates private members and active bindings
MyClass <- R6Class("MyClass",
private = list(
x = 2,
# Private methods can access public members
prod_xy = function() x * y
),
public = list(
y = 3,
initialize = function(x, y) {
if (!missing(x)) private$x <- x
if (!missing(y)) self$y <- y
},
# Set a private variable
set_x = function(value) private$x <- value,
# Increment y, and return self
inc_y = function(n = 1) {
y <<- y + n
invisible(self)
},
# Access private and public members
sum_xy = function() x + y,
# Access a private variable and private method
sumprod = function() x + prod_xy()
),
active = list(
y2 = function(value) {
if (missing(value)) return(y * 2)
else self$y <- value/2
}
)
)
z <- MyClass$new(5)
z$sum_xy() # 8
z$sumprod() # 20
# z$x <- 20 # Error - can't access private member directly
z$set_x(20)
z$sum_xy() # 23
z$y <- 100 # Can set public members directly
z$sum_xy() # 120
z$y2 # An active binding that returns y*2
z$y2 <- 1000 # Setting an active binding
z$y # 500
# Methods that return self allow chaining
z$inc_y()$inc_y()
z$y # 502
# Print, using the print.R6Class method:
print(z)
Run the code above in your browser using DataLab