[R] A question on S7

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Tue Dec 23 01:59:01 CET 2025


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 using y) ){
        if(length(value))self using y <- value
        else self using y <- self using 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 using 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."



More information about the R-help mailing list