15

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()
Abiel
  • 5,251
  • 9
  • 54
  • 74

2 Answers2

15

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)

bergant
  • 7,122
  • 1
  • 20
  • 24
  • See also [github.com/r-lib/R6#66 : Consider adding static methods/fields (issue open)](https://stackoverflow.com/questions/28916460/static-methods-in-r6-classes) – phili_b Aug 07 '19 at 17:43
1

I have used a workaround for the solution. You can access the methods without creating the instance by calling MyClass$public_methods$my_static_method(). To restrict the calls without the instance, I have made self as an argument in all of the methods.

Code Maverick
  • 20,171
  • 12
  • 62
  • 114
user2855892
  • 81
  • 1
  • 3
  • 9
  • 1
    So you made every instance method and every call to an instance method more complex by adding a redundant argument? Doesn't that kind of beat the purpose of the whole R6 class system? The developers of R6 invested a lot of time and ingenuity to make sure that the instance methods get their context without needing a 'self' argument. – Roland Weber Jan 10 '19 at 09:54