Can we get R6 class name from inside the class?

83 Views Asked by At

I need to get the name of the R6 class variable from inside the class. Can I do that? - like in example below:

  Simple <- R6Class(  "Simple",
                      public = list(
                        myname = NA,
                        dt = NA, 
                        initialize = function () {
                          self$myname = substitute(self)
                        }
                      )              
  )
  mysimple <- Simple$new()  
  mysimple$myname 

This returns self. And i want this to return mysimple.

This would be useful for storing a class variable with saveRDS() and then restoring it with saveRDS()

1

There are 1 best solutions below

0
nrennie On

Yes, you can use class(self)[1] e.g.

Simple <- R6Class(
  "Simple",
  public = list(
    getClass = function(){
      class(self)[1]
    }
  )
)

mysimple <- Simple$new()

mysimple$getClass()

Based on the solution in the GitHub issues: https://github.com/r-lib/R6/issues/135