Skip to content

S4 'properties' - creating 'slot' functions?

2 messages · ¨Tariq Khan, Martin Morgan

#
Hi Tariq

Some discussion of this topic a while ago on the R-devel newsgroup;
bottom line is that there is no consensus and a certain amount of
resistance to make R conform to the implementation of other languages
(and not exploit R's unique strengths).

https://stat.ethz.ch/pipermail/r-devel/2006-September/042854.html
https://stat.ethz.ch/pipermail/r-devel/2006-September/042864.html

You could implement something fancier (e.g., a method for "$" or "[["
or "@" or a suite of generics "get_x"), but I kind of like (because
'slot' is a function with a well-defined purpose, so why not make it a
generic?)

setGeneric("slot")

setMethod("slot",
          signature=signature(object="A", name="character"),
          function(object, name)
          ## do anything, e.g., restrict access to specific slots
          ## alternatively, dispatch on name with 'switch'
          if (name %in% slotNames(class(object))) callNextMethod()
          else stop("slot '", name, "' undefined"))

setGeneric("slot<-",
           signature=c("object", "name", "value"))

setReplaceMethod("slot",
                 signature(object="A", name="character", value="ANY"),
                 function(object, name, check=TRUE, value)
                 if (name %in% slotNames(class(object))) callNextMethod()
                 else stop("slot '", name, "' cannot be assigned"))

and then
+          representation=representation(x="numeric"))
[1] "A"
Error in slot(a, "y") : slot 'y' undefined
[1] 5 4 3 2 1

A class could be defined to implement the dispatch, so other classes
just have to inherit from that.

Discussion may be veering toward the R-devel newsgroup.

Martin

"?Tariq Khan" <tariq.khan at gmail.com> writes: