Search code examples
rr6

Difference between self and private method call in R6


Lately I found myself coding some stuff in R6, and while having fun handling some objects an interesting question came out. When creating a private method (e.g. foo, of the bar) and calling it inside other public methods it works if I either call it using:

self$foo

and

private$foo

What I am asking is: what is the difference between those two ways of calling a method in R6? Thank you in advance!


Solution

  • From the "Introduction to R6 classes" vignette (emphasis mine):

    self

    Inside methods of the class, self refers to the object. Public members of the object (all you’ve seen so far) are accessed with self$x

    private

    Whereas public members are accessed with self, like self$add(), private members are accessed with private, like private$queue.

    So, even if you can access private methods through self, you should do it through private. Don't rely on behavior which may go away, seeing as how the documentation says it shouldn't work like that.

    That said, I can't access private methods using self:

    library(R6)
    
    bar <- R6Class("bar",
      private = list(
        foo = function() {
          message("just foo it")
        }
      ),
      public = list(
        call_self = function() {
          self$foo()
        },
        call_private = function() {
          private$foo()
        }
      )
    )
    
    b <- bar$new()
    b$call_private()
    # just foo it
    b$call_self()
    # Error in b$call_self() : attempt to apply non-function