2

I can make a parent class containing an object

setRefClass("img",fields=list(name="character"))
setRefClass("imgs",fields=list(img="img"))

However, I want to create an RefClass object with an array of other RefClass objects. I can use a "list" as place holder and fill it in manually, but is there a better way?

For example, can a "list" type be specified to hold a certain object in it? Hypothetically, something like this: (but doesn't work)

setRefClass("img",fields=list(name="character"))
setRefClass("imgs",contains=list(imgList=list("img")))

I am hoping that when I call a method on "imgList", it knows to call method for each "img" element.

csgillespie
  • 59,189
  • 14
  • 150
  • 185
Sang
  • 535
  • 5
  • 14

1 Answers1

0

You can use setValidity to ensure each element in a list is a certain class.

img <- setRefClass("img", fields = list(name = "character"))
imgs <- setRefClass("imgs", fields = list(imgList = "list"))
validImgs <- function(object) {
  if (length(object$imgList) == 0) {
    stop("`imgs` must contain at least one object of class `img`.")
  }
  sapply(object$imgList, function(x) {
    if (class(x)[1] != "img") {
      stop("Each element in `imgList` must be of class `img`")
    }
  })
  T
}
setValidity("imgs", validImgs)

Here are two examples of imgs failing validation.

# An invalid image object.
imgs$new(imgList = list())

Error in validityMethod(object) : imgs must contain at least one object of class img.

# Another invalid image object.
imgs$new(imgList = list(1))

Error in FUN(X[[i]], ...) : Each element in imgList must be of class img

Here is an example of imgs passing validation.

# A valid image object.
imgs$new(imgList = list(img$new()))

Reference class object of class "imgs"
Field "imgList":
[[1]]
Reference class object of class "img"
Field "name":
character(0)
Joshua Daly
  • 606
  • 1
  • 7
  • 16