[Rd] Question about copying reference objects using the initialize method

Aleix Ruiz de Villa aleixrvr.info at gmail.com
Mon Oct 31 16:53:27 CET 2011


Dears,

I have a question about copying reference objects using the initialize method.

1) If the latter has no arguments, there is no problem to copy an object.

myClass = setRefClass("myClass", fields = list(value = "numeric") )

myClass$methods(initialize = function(...){

  value <<- 1

  callSuper(...)
})

newObject = myClass$new()
newObject$value = 2
copyObject = newObject$copy()
copyObject$value = 3
print(newObject$value)
print(copyObject$value)


2) However, if the initialize method has arguments, I get an error:

myClass = setRefClass("myClass", fields = list(value = "numeric") )
myClass$methods(initialize = function(extValue, ...){

  value <<- extValue

  callSuper(...)
})
newObject = myClass$new(extValue = 2)
copyObject = newObject$copy()

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


I understand that copy() first builds another instance of the object
and then copies the fields. But it calls new without arguments...

3) One solution would be the initialize values by default

myClass = setRefClass("myClass", fields = list(value = "numeric") )

myClass$methods(initialize = function(extValue = 1, ...){

  value <<- extValue

  callSuper(...)
})

newObject = myClass$new(extValue = 2)
copyObject = newObject$copy()


But I have a long list of arguments, so this way would be a little
uncomfortable. On the other hand, I've been told that in OOP, the idea
of the initialise method is to use the minimum information to build
the oject. So passing a long list of arguments is not a good idea.


4) Another option is to first build the object and then set the parameters

myClass = setRefClass("myClass", fields = list(value = "numeric") )

myClass$methods(setPar = function(extValue = 1, ...){

  value <<- extValue

  return()
})

newObject = myClass$new()
newObject$setPar(extValue = 2)
copyObject = newObject$copy()


It works fine.

Anyway I am curious to know if there is any way to use the initialize
method with arguments that is not a problem with copy().


Thank!

Aleix Ruiz de Villa



More information about the R-devel mailing list