9

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

Which throws an error:

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

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

Nicholas Hamilton
  • 10,044
  • 6
  • 57
  • 88

1 Answers1

9

Thought I would post my answer, I assign the class 'IAddable' to both R6 prototypes (sort of like interface declaration in other languages)

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

Then we can assign a single overloaded operator, which will be called by all objects that inherit from this interface class declaration.

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

This then works as expected:

a = A$new()
b = B$new()

a + b  #WORKS, RETURNS a
b + a  #WORKS, RETURNS b
Nicholas Hamilton
  • 10,044
  • 6
  • 57
  • 88