# Simple properties store data inside an object
pizza <- new_class("pizza", properties = list(
slices = new_property(class_numeric, default = 10)
))
my_pizza <- pizza(slices = 6)
my_pizza@slices
my_pizza@slices <- 5
my_pizza@slices
your_pizza <- pizza()
your_pizza@slices
# Dynamic properties can compute on demand
clock <- new_class("clock", properties = list(
now = new_property(getter = function(self) Sys.time())
))
my_clock <- clock()
my_clock@now; Sys.sleep(1)
my_clock@now
# This property is read only
try(my_clock@now <- 10)
# These can be useful if you want to deprecate a property
person <- new_class("person", properties = list(
first_name = class_character,
firstName = new_property(
getter = function(self) {
warning("@firstName is deprecated; please use @first_name instead", call. = FALSE)
self@first_name
},
setter = function(self, value) {
warning("@firstName is deprecated; please use @first_name instead", call. = FALSE)
self@first_name <- value
self
}
)
))
hadley <- person(first_name = "Hadley")
hadley@firstName
hadley@firstName <- "John"
hadley@first_name
Run the code above in your browser using DataLab