Operator overload R, R6

Consider the following:

A = R6::R6Class("ClassA") B = R6::R6Class("ClassB") `+.ClassA` = function(o1,o2) o1 #Trivial Example, Usually do something `+.ClassB` = function(o1,o2) o1 #Trivial Example, Usually do something a = A$new() b = B$new() a + b 

What causes the error:

 Warning: Incompatible methods ("+.ClassA", "+.ClassB") for "+" Error in a + b : non-numeric argument to binary operator 

How can this be resolved, so both A and B can overload the + operator and be added together.

+6
source share
1 answer

I think I will send my answer, I will assign the class 'IAddable' for both R6 prototypes (sort of like declaring an interface in other languages)

 A = R6::R6Class(c("ClassA","IAddable")) B = R6::R6Class(c("ClassB","IAddable")) 

Then we can assign one overloaded statement that will be called by all objects that inherit from this declaration of the interface class.

 `+.IAddable` = function(o1,o2) o1 #Trivial Example, Usually do something 

This works as expected:

 a = A$new() b = B$new() a + b #WORKS, RETURNS a b + a #WORKS, RETURNS b 
+5
source

All Articles