Search code examples
rreference-class

Private Members in R Reference Class


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


Solution

  • 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,

    Account = setRefClass("ref_Account", 
                           fields = list(number = "character"),
                           methods = list(
                               initialize = function(balance, number) {
                                   .self$number = number
                                   .self$balance = balance
                               })
    

    As before, we'll create an instance:

    tb <- Account$new(balance=50.75, number="baml-0029873")
    ##No balance
    tb
    
    Reference class object of class "ref_Account"
    Field "number":
    [1] "baml-0029873"
    

    As I mentioned, it isn't truly private, since you can still do:

    R> tb$balance
    [1] 50.75
    R> tb$balance = 12 
    R> tb$balance
    [1] 12