[Rd] Surprising behavior when using the reference class with the dollar symbol
Jiefei Wang
@zwj|08 @end|ng |rom gm@||@com
Sat Mar 27 15:49:19 CET 2021
Thanks, Duncan. Below is the repost of my question in plain text mode.
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 OK
x$a
## This is OK
`$`(x, "a")
## But this is not OK
i <- "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
On Sat, Mar 27, 2021 at 10:20 PM Duncan Murdoch
<murdoch.duncan using gmail.com> wrote:
>
> 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 using r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-devel
> >
>
More information about the R-devel
mailing list