Question

I have created a setRefClass, I would like to know how you can implement the accessors so that when you create a new instance of this class you can access the fields by using setXXX, getXXX. I was thinking of using .self$accessors(names(.self$fields())) in initialize method but it doesn`t seem to work.

pathRoot <- setRefClass(
    Class = "pathRoot",
    fields = list(
            # basic info of path
            W = "character",
            Y = "character",
            H = "character"
            ),
    )
Was it helpful?

Solution

To automatatically generate getters and setters, just use the accessors method:

pathRoot$accessors(c("W", "Y", "H"))

Example

p = pathRoot$new(W="A",Y="B",H="C")
R> p$getY()
[1] "B"
R> p$setW("Hi")
R> p$getW()
[1] "Hi"

You can also access the variables via the $, e.g.

p$W
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top