Let's say I have a constructor of a class with two properties with one initiated and the other set to NULL
:
myclass <- function(data) {
structure(
list(data1 = data,
data2 = NULL),
class = "myclass")
}
And a generic:
myadd <- function(obj, x) {
UseMethod("myadd")
}
myadd.myclass <- function(obj, x) {
obj$data2 = obj$data1 + x
}
When I do:
mc = myclass(1)
myadd(mc, 2)
The property data2
does not change:
> mc
$data1
[1] 1
$data2
NULL
attr(,"class")
[1] "myclass"
Obviously, when I assign the result to a variable:
tmp = myadd(mc, 2)
I get the result:
> tmp
[1] 3
How to modify the property of an existing object with a generic function? Is it even kosher to do so?
I'm guessing I'm missing some crucial piece of info about S3 classes in R or about OOP in general. Any tips appreciated.