R6Class - Encapsulation issue: Bad design?

自作多情 提交于 2021-02-07 10:49:17

问题


Minimal example

Attaching R6 package

require(R6)

Element class definition

element_factory <- R6Class(
  "Element",
  private = list(
    ..value = 0),
  active = list(
    value = function(new) {
      if(missing(new))
        private$..value
      else private$..value <- new}))

Container class definition

container_factory <- R6Class(
  "Container",
  private = list(
    ..element = element_factory$new()
  ),
  active = list(
    element = function() private$..element))

Creating container istance

co <- container_factory$new()

Accessing element and element field

> co$element

<Element>
   Public:
   clone: function (deep = FALSE)
     initialize: function (value = 0)
       value: active binding
Private:
  ..value: 0

> co$element$value

[1] 0

Modifying value field in element object

Throws an error
> co$element$value <- 3

Error in (function ()  : unused argument (base::quote(<environment>))
But the value is modified
> co$element

<Element>
   Public:
   clone: function (deep = FALSE)
     initialize: function (value = 0)
       value: active binding
Private:
  ..value: 3

Question

What does this error mean and how to prevent it?


EDIT:

I have found a workaround but I still do not understand the initial error:

elt <- co$element
elt$value <- 3

This works and does not throw an error.

I am also surprised that the following code throws another error:

(co$element)$value <- 3

Error in (co$element)$value <- 3 : could not find function "(<-"

来源:https://stackoverflow.com/questions/60577261/r6class-encapsulation-issue-bad-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!