Search code examples
rreference-class

In R, how to print values of fields in a ReferenceClass?


I have a ReferenceClass in R.

How can I add a method "print()" to it, which will print the values of all of the fields in the class?


Solution

  • Perhaps a better implementation is the following

    Config = setRefClass("Config",
      fields = list(    
        ConfigBool = "logical", 
        ConfigString = "character"),
      methods = list(
        ## Allow ... and callSuper for proper initialization by subclasses
        initialize = function(...) {
            callSuper(..., ConfigBool=TRUE, ConfigString="A configuration string")
            ## alterantive:
            ##    callSuper(...)
            ##    initFields(ConfigBool=TRUE, ConfigString="A configuration string")
        },
        ## Implement 'show' method for automatic display
        show = function() {
            flds <- getRefClass()$fields()
            cat("* Fields\n")
            for (fld in names(flds))  # iterate over flds, rather than index of flds
                cat('  ', fld,': ', .self[[fld]], '\n', sep="")
        })
      )
    

    The following illustrates use of the Config constructor (no need to invoke 'new') and automatic invocation of 'show'

    > Config()
    * Fields
      ConfigBool: TRUE
      ConfigString: A configuration string