Jiefei Wang
2021-Mar-27 14:16 UTC
[Rd] Surprising behavior when using the reference class with the dollar symbol
Hi all, I'm trying to get the field value of a reference object by the field name, but the dollar symbol behaves quite unusual. See example below *.foo <- setRefClass( "foo", fields = list( a = "integer" ))x <- .foo$new(a=1L)## This is OKx$a## This is OK`$`(x, "a")## But this is not OKi <- "a"`$`(x, i)* For the last line of code I get this error *Error in envRefInferField(x, what, getClass(class(x)), selfEnv) : ?i? is not a valid field or method name for reference class ?foo?* It looks like when calling the dollar symbol using the function format, it treats the input argument as a character literal and does not evaluate it inside the function. I know we have the function `field` to get the slot variable, but I wonder if this is designed on purpose as the above example works for both list and S4 system. Best, Jiefei [[alternative HTML version deleted]]
Duncan Murdoch
2021-Mar-27 14:20 UTC
[Rd] Surprising behavior when using the reference class with the dollar symbol
On 27/03/2021 10:16 a.m., Jiefei Wang wrote:> Hi all, > > I'm trying to get the field value of a reference object by the field name, > but the dollar symbol behaves quite unusual. See example below > > > > > > > > > > > > > > > *.foo <- setRefClass( "foo", fields = list( a = "integer" > ))x <- .foo$new(a=1L)## This is OKx$a## This is OK`$`(x, "a")## But this is > not OKi <- "a"`$`(x, i)*This is really hard to read. Please post it again, but don't use HTML. Duncan Murdoch> > For the last line of code I get this error > > > *Error in envRefInferField(x, what, getClass(class(x)), selfEnv) : ?i? is > not a valid field or method name for reference class ?foo?* > > It looks like when calling the dollar symbol using the function format, it > treats the input argument as a character literal and does not evaluate it > inside the function. I know we have the function `field` to get the slot > variable, but I wonder if this is designed on purpose as the above example > works for both list and S4 system. > > Best, > Jiefei > > [[alternative HTML version deleted]] > > ______________________________________________ > R-devel at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-devel >