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()
R6 is an implemention of encapsulated object-oriented programming for R, and is a simpler, faster, lighter-weight alternative to R's built-in reference classes. This style of programming is also sometimes referred to as classical object-oriented programming. Some features of R6: R6 objects have reference semantics.
From the "Introduction to R6 classes" vignette (emphasis mine): self. Inside methods of the class, self refers to the object. Public members of the object (all you've seen so far) are accessed with self$x. private.
Create a new R6 class object that on multipication of numbers. The class name and the result of class must be same always, as the R6Class() returns a R6 object that defines the class. We can then construct a new object from the class using the new() method which is accessed using the $ operator.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With