Static methods in R6 classes

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

MyClass$method() 

Instead

 myinstance <- MyClass$new() myinstance$method() 
+7
r r6
source share
2 answers

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

how

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

But the method does not work on the class instance :

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

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

+6
source share

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

0
source share

All Articles