Search code examples
rr-s4

What the equivalent of "this" (as in Java or C++) in S4 object system in R


Now I understand that the S4 object system of R is very different from C++ or Java.

However I had the question is there anything similar to the "this" in S4


Solution

  • Methods are defined on generics and dispatch on class, rather than on classes. So this is always the object being dispatched on.

    .A = setClass("A", slots = c(a = "integer"))
    
    setGeneric("foo", function(x) standardGeneric("foo"))
    
    setMethod("foo", "A", function(x) {
       x@a        # 'x' is the object that `foo()` dispatches on, i.e., 'this'
    })
    

    Usage:

    > y = .A(a=1:5)
    > foo(y)
    [1] 1 2 3 4 5