Search code examples
rr6

Static methods in R6 classes


Is there a way to add static methods to R6 classes? For example, a function that can be called like

MyClass$method()

Instead of

myinstance <- MyClass$new()
myinstance$method()

Solution

  • I'm not an expert on R6 but since every R6 class is an environment, you can add anything you want to this environment.

    Like:

    MyClass$my_static_method <- function(x) { x + 2}
    MyClass$my_static_method(1)
    #[1] 3
    

    But the method will not work on the instance of the class:

    instance1 <- MyClass$new()
    instance1$my_static_method(1)
    # Error: attempt to apply non-function
    

    You should be careful with the existing objects in the class environment. To see what is already defined use ls(MyClass)