[Rd] Reference classes
Jon Clayden
jon.clayden at gmail.com
Sat Oct 23 01:52:02 CEST 2010
On 22 October 2010 18:55, John Chambers <jmc at r-project.org> wrote:
>> As a suggestion, it would be nice if the accessors() method could be
>> used to create just "getters" or just "setters" for particular fields,
>> although I realise this can be worked around by removing the unwanted
>> methods afterwards.
>
> In other words, read-only fields. There is a facility for that implemented
> already, but it didn't yet make it into the documentation, and it could use
> some more testing. The generator object has a $lock() method that inserts a
> write-once type of method for one or more fields. Example:
>
>> fg <- setRefClass("foo", list(bar = "numeric", flag = "character"),
> + methods = list(
> + addToBar = function(incr) {
> + b = bar + incr
> + bar <<- b
> + b
> + }
> + ))
>> fg$lock("bar")
>> ff = new("foo", bar = 1.5)
>> ff$bar <- 2
> Error in function (value) : Field "bar" is read-only
>
> A revision will document this soon.
>
> (And no, the workaround is not to remove methods. To customize access to a
> field, the technique is to write an accessor function for the field that, in
> this case, throws an error if it gets an argument. See the documentation
> for the fields argument. The convention here and the underlying mechanism
> are taken from active bindings for environments.)
OK, yes - I see. This is clearly much less superficial than removing
the setter method for a field which can be directly set anyway. I'll
have to try out field accessor functions and get a feel for the
semantics.
Many thanks for the rapid and very helpful response.
Regards,
Jon
More information about the R-devel
mailing list