r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
405 stars 56 forks source link

Error message when trying to set read-only active bindings #99

Closed richierocks closed 7 years ago

richierocks commented 7 years ago

If I create a class with a read-only active binding, then try to set the value, the error message is a bit obscure. To reproduce:

library(R6)
thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value"
  ),
  active = list(
    a_field = function() {
      private$..a_field
    }
  )
)
a_thing <- thing_factory$new()
a_thing$a_field <- "a new value"
## Error in (function ()  : unused argument (quote("a new value"))

It would be clearer for the user if the message explained that a_field was read-only.

wch commented 7 years ago

Unfortunately, this is what R does with active bindings:

e <- new.env()
makeActiveBinding("x", function() { 1 }, e)
e$x <- 2
# Error in (function ()  : unused argument (quote(2))

I wish there were a straightforward way to make nicer error messages, but I don't think it's possible without changing code in R itself.

richfitz commented 7 years ago

What about:

e <- new.env()
makeActiveBinding("x", function(value) {
  if (!missing(value)) {
    stop("x is read only", call. = FALSE)
  }
  1
}, e)
e$x
e$x <- 2