Exscuse my naive question, it is my first attempt on R6.
I want to create a subclass (Farmer) that inherits from Person, but has a default value for job.
I tried this, but it will not work:
Person <- R6Class("Person", list(
name = NULL,
job = NA,
initialize = function(name, job = NA) {
stopifnot(is.character(name), length(name) == 1)
stopifnot(is.character(job), length(job) == 1)
self$name <- name
self$job <- job
}
))
Farmer= R6Class("Farmer",
inherit = Person,
public = list(
job1=function(){
self$job= "farm"
}
))
Is it possible to set the default value, since I cannot use initialise on the subclass? Thank you!!
You can redefine the initialize
method in your Farmer
class. In this redefined method, you can call the initialize
method from the super
class (in your case Person
) and set a default for job
, while just passing all other arguments:
Farmer <- R6Class("Farmer",
inherit = Person,
public = list(
initialize = function(...) {
super$initialize(
job = "farm",
...
)
}
)
)