2

It seems that if we create a class B that inherits from class A, A's constructor is called when B is being created. This leads to the following problem - A may have a mandatory parameter in its ctor (for use during instantiation), and so running the following:

A <- setRefClass("A", 
    methods = list(
        initialize = function(mandatoryArg) {
            print(mandatoryArg)
        }
    )
)

B <- setRefClass("B", contains = "A")

I get the error

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

This seems very strange - why is this happening and what can I do about this?

mchen
  • 9,808
  • 17
  • 72
  • 125

1 Answers1

1

The implicit requirement is that the constructor with no arguments (e.g., A()) succeeds, so provide a default value for mandatoryArg

A <- setRefClass("A", 
    methods = list(
        initialize = function(mandatoryArg=character()) {
            print(mandatoryArg)
        }
    )
)

or (recommended) avoid using the initialize method for construction but instead define a user-friendly wrapper

.A <- setRefClass("A", fields=list(mandatoryField="character"))

A <- function(mandatoryArg, ...) {
    if (missing(mandatoryArg))
        stop("'mandatoryArg' missing")
    .A(mandatoryField=mandatoryArg, ...)
}

.B <- setRefClass("B", contains="A")

B <- function()
    .B()

or B <- function() .B(mandatoryField="foo") or B <- function() .B(A("mandatoryField"))

Martin Morgan
  • 45,935
  • 7
  • 84
  • 112