[R-pkg-devel] Assigning values to fields in Reference Classes

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Mon May 11 20:58:31 CEST 2020


What does this have to do with package development? Seems more like a
query for r-help.

Cheers,
Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )

On Mon, May 11, 2020 at 11:27 AM Per Nyfelt <per using alipsa.se> wrote:
>
> Hi,
>
> I have been playing with alternative ways to assign values to fields in
> reference classes.
>
> Besides the "standard" <<- there are two other ways that also "seems to
> work". One is using .self$fieldName assigned with <- and the the other
> one is field(fieldName, value).
>
> With regards to the ".self method" (example below): is this a "safe"
> equivalent to <<- i.e. are these two ways identical in result and
> possible "side effects"?
>
> StandardAssignment <- setRefClass(
>    Class ="StandardAssignment",
>    fields = list(
>      m_attributes = "list"
>    ),
>    methods = list(
>      setAttribute = function(name, value) {
>        m_attributes[[as.character(name)]] <<- as.character(value)
>        return(invisible(.self))
>      },
>      getAttribute = function(name) {
>        m_attributes[[name]]
>      }
>    )
> )
>
> s1 <- StandardAssignment$new()
> s1$setAttribute("name", "foo")
> s1$getAttribute("name")
>
> [1] "foo"
>
> SelfAssignment <- setRefClass(
>    Class ="SelfAssignment",
>    fields = list(
>      m_attributes = "list"
>    ),
>    methods = list(
>      setAttribute = function(name, value) {
>        .self$m_attributes[[as.character(name)]] <- as.character(value)
>        return(invisible(.self))
>      },
>      getAttribute = function(name) {
>        m_attributes[[name]]
>      }
>    )
> )
>
> s2 <- SelfAssignment$new()
> s2$setAttribute("name", "foo")
> s2$getAttribute("name")
>
> [1] "foo"
>
>
> Best regards,
>
> Per
>
> ______________________________________________
> R-package-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-package-devel



More information about the R-package-devel mailing list