December 2017
Beginner to intermediate
470 pages
12h 29m
English
Active bindings look like fields, but each time they are accessed, they call a function. They are always publicly visible and are similar to Python's properties. If we wanted to implement the color() method as an active binding, we could use the following code. As you can see, you can either get or set the color attribute, without using an explicit method call (note the missing parentheses):
R6Rectangle <- R6Class(
"R6Rectangle",
public = list(
...
),
private = list(
...
),
active = list(
color = function(new_color) {
if (missing(new_color)) {
return(private$own_color)
} else {
private$own_color <- new_color
}
}
)
)
R6_rectangle <- R6Rectangle$new(2, 3, "blue")
R6_rectangle$color
#> [1] "blue"
R6_rectangle$color <- "black" ...