3

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"
            ),
    )
csgillespie
  • 59,189
  • 14
  • 150
  • 185
pam
  • 676
  • 1
  • 7
  • 27

1 Answers1

3

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
csgillespie
  • 59,189
  • 14
  • 150
  • 185
  • 1
    Is there any way to add it inside the definition of the class? – pam Feb 28 '13 at 10:33
  • I don't think so (but I've never really thought about it). I usually define the class and just add the `accessors` line underneath it. – csgillespie Feb 28 '13 at 10:38
  • ok, i will go for the line underneath but it is not very clean (my opinion). thx for your help – pam Feb 28 '13 at 10:39