Search code examples
rclasstostringr6

How can I overwrite the to string method of an R6Class in R language?


I've tried by adding a to_string() function to the public part of the Class, but I'm looking for a method, like override in C#.


Solution

  • toString() is an S3 geneic, so it can be defined for your class using toString.{className}

    MyClass <- R6::R6Class(
      "MyClass",
      list(i = 0)
    )
    
    toString.MyClass <- function(x, ...) {
      paste("i is", x$i)
    }
    
    my_object <- MyClass$new()
    toString(my_object)
    #> [1] "i is 0"
    my_object$i <- 1
    toString(my_object)
    #> [1] "i is 1"
    

    You can see it is a S3 generic by looking at the source

    toString
    #> function (x, ...) 
    #> UseMethod("toString")
    #> <bytecode: 0x55fb2afe7d68>
    #> <environment: namespace:base>
    

    UseMethod means it will forward the call based on the class of the first argument (x) and if no implementation of toString for the specific class is given, toString.default() will be invoked instead.