RConsortium / S7

S7: a new OO system for R
https://rconsortium.github.io/S7
Other
399 stars 33 forks source link

`S7_data<-` doesn't allow updating attributes like `names` #478

Open t-kalinowski opened 3 days ago

t-kalinowski commented 3 days ago

Note that the name of the 3rd entry is missing after updating.

library(S7)
write_once_list <- new_class("write_once_list",
  class_list,
  constructor = function(...) new_object(list(...)),
  validator = function(self) {
    if(anyDuplicated(nms <- names(self)))
      paste0("names not all unique. duplicates: ",
             paste0(unique(nms[duplicated(nms)]), collapse = ", "))
  }
)

method(`$<-`, write_once_list) <- 
method(`[[<-`, write_once_list) <- function(x, name, value) {
  .x <- S7_data(x)
  if (hasName(.x, name))
    stop("entry exists: ", name)
  .x[[name]] <- value
  S7_data(x) <- .x
  x
}

w <- write_once_list(x = 3, y = 4)

w
#> <write_once_list> List of 2
#>  $ x: num 3
#>  $ y: num 4
w$bar <- 1

w
#> <write_once_list> List of 3
#>  $ x : num 3
#>  $ y : num 4
#>  $ NA: num 1