Search code examples
rprivate-methodsr6public-members

How to access public members in private method in R6Class?


library(R6)

Person<-R6Class("Person",
    public=list(
      name=NULL,
      age=NULL,
      initialize=function(name,age){
        self$name<-name
        self$age<-age
      },
      GrowUP1=function(){
        self$publicGrow()
      },
      publicGrow=function(){
        self$age<-self$age+1
      },
      GrowUP2=function(){
        self$privateGrow()
      }
    ),
    private=list(
      privateGrow=function(){
        self$age<-self$age+1
      }
    )
)

Person<-Person$new('Tom',20)
Person$age
Person$GrowUP1()
Person$age
Person$GrowUP2()    

This is my sample code. I run last code Person$GrowUP2(). But, I got error Error in Person$GrowUP2() : attempt to apply non-function

I do not know why this code is not running.I want to use private method in order to modify public member.How to


Solution

  • Call the private functions using private:

    GrowUP2=function(){
            private$privateGrow()
            }
    
    Person<-Person$new('Tom',20)
    Person$GrowUP1()
    Person$GrowUP2() 
    Person$age
    
    [1] 22