I defined two classes that can successfully add two of their own objects or a number and one of their own objects.
a <- structure(list(val = 1), class = 'customClass1')
b <- structure(list(val = 1), class = 'customClass2')
`+.customClass1` <- function(e1, e2, ...){
val1 <- ifelse(is.numeric(e1), e1, e1$val)
val2 <- ifelse(is.numeric(e2), e2, e2$val)
val_res <- val1 + val2
print('customClass1')
return(structure(list(val = val_res), class = 'customClass1'))
}
`+.customClass2` <- function(e1, e2, ...){
val1 <- ifelse(is.numeric(e1), e1, e1$val)
val2 <- ifelse(is.numeric(e2), e2, e2$val)
val_res <- val1 + val2
print('customClass2')
return(structure(list(val = val_res), class = 'customClass1'))
}
print.customClass1 <- function(x, ...){
print(x$val)
}
print.customClass2 <- function(x, ...){
print(x$val)
}
a + a
# [1] 2
a + 1
# [1] 2
b + b
# [1] 2
1 + b
# [1] 2
But obviously, it goes wrong when I try to add the two custom classes.
a + b
# Error in a + b : non-numeric argument to binary operator
# In addition: Warning message:
# Incompatible methods ("+.customClass1", "+.customClass2") for "+"
I could define just one function for customClass1, but then that function would not work when I try to add two customClass2 objects. Is there any way to prioritize one function over the other?
R seems to do this naturally by prioritizing my functions over the base functions (e.g. of the type numeric or integer). When one of both arguments has the customClass type, R automatically redirects it to my function instead of the default function.