Is it possible to have private member fields inside of an R reference class. Playing with some of the online examples I have:
> Account <- setRefClass( "ref_Account"
> , fields = list(
> number = "character"
> , balance ="numeric")
> , methods = list(
> deposit <- function(amount) {
> if(amount < 0) {
> stop("deposits must be positive")
> }
> balance <<- balance + amount
> }
> , withdraw <- function(amount) {
> if(amount < 0) {
> stop("withdrawls must be positive")
> }
> balance <<- balance - amount
> }
> ) )
>
>
> tb <- Account$new(balance=50.75, number="baml-029873") tb$balance
> tb$balance <- 12
> tb$balance
I hate the fact I can update the balance directly. Perhaps that the old pure OO in me, I really would like to be able make the balance private, at least non-settable from outside the class.
Thoughts
This answer doesn’t work with R > 3.00, so don’t use it!
As has been mentioned, you can’t have private member fields. However, if you use the initialize method, then the balance isn’t displayed as a field. For example,
As before, we’ll create an instance:
As I mentioned, it isn’t truly private, since you can still do: