Apologies if I missed this in the docs (vignettes & help files) --
please let me know where I should look if so.
My concern is that my solution to the problem that I will state relies
on undocumented behavior that might change in future.
The problem: Suppose I wish to define a class that will have 2
properties, "x" and "y". When I invoke the default (not a custom)
constructor but omit a value for y in the call, I want the "default"
to be the value of x. After constructing the object, I want y to be
"frozen" at its initial value. Following the "class & object" vignette
(I think), I can do this using a setter for y as follows:
---------------------------
test <- new_class("test", properties = list(
x = new_property(class_numeric),
y = new_property(class_numeric,
setter = function(self, value){
if(is.null(self@y) ){
if(length(value))self@y <- value
else self@y <- self@x
}
self ## ignores value if attempt to change y
}
)))
-----------------------------------------
This seems to work:
#.> test(2)
<test>
@ x: num 2
@ y: num 2
#.> z <-test(2,3)
#.> z
<test>
@ x: num 2
@ y: num 3
#.> z@y <- 5
#.> z
<test>
@ x: num 2
@ y: num 3 ## y is unchanged
---------------------------------------------
My questions:
1) Is this legit? -- i.e. makes no use of undocumented stuff that could change?
2) Is there a "better" way to do this?
Best to all and Happy Holidays (to those for whom this is relevant),
Bert
"An educated person is one who can entertain new ideas, entertain
others, and entertain herself."
______________________________________________
[email protected] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.