mto_19
mto_19

Reputation: 195

Assigning to .self in reference class initialize

I'm trying to define a hybrid initialize function that can either takes a numeric argument or an object of the same class (similar to "copy-constructor" in other languages). My attempt:

    setRefClass("Temp",
        fields=list(
          x="numeric",
          y="ANY"),
        methods=list(initialize=function(object){
          if (class(object) == "numeric"){
            .self$x <- object
            .self$y <- NULL
          }
          else if (class(object) == "Temp"){
            print("Copy")
            .self <- object
            #.self <- object$copy()
          }
          else{
            stop(paste0("Class '",class(object),"' unknown"))
          }
        }
        ))

So if object is numeric, it is assigned to .self$x and .self$y is initialized to NULL. If object has class "Temp", then initialize should construct a deep copy of object.

However, .self <- object doesn't do anything. If I run

    temp1 <- new("Temp",1)
    temp2 <- new("Temp",temp1)

Then temp2 is initialized to default values. If instead I use .self <- object$copy(), then I get

    Error in .Object$initialize(...) : argument "object" is missing, with no default

which probably happens because $copy() calls initialize().

What is the correct code for what I tried to achieve with .self<-object?

Upvotes: 0

Views: 177

Answers (0)

Related Questions