I developed a package where reference classes is used a lot. When submitting it to CRAN i got the feedback that  i should not use <<- as that was "modifying the global environment". That was a misunderstanding that was sorted out but before it was, I started to investigate alternative ways to assign values to refclass fields. I can it this elsewhere since it does not belong.

Thanks,

Per

On 5/11/20 8:58 PM, Bert Gunter wrote:
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 <p...@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@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-package-devel

______________________________________________
R-package-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-package-devel

Reply via email to