如何禁止 S4 对象的空槽?

How can I disallow empty slots for S4 objects?

假设我有一个 class 定义如下:

setClass("myclass", slots = list(id="character"))

我希望 id 是强制性的,myclass 没有 id 是无效对象。目前,我得到以下信息:

> new("myclass")
An object of class "myclass"
Slot "id":
character(0)

我希望设置验证函数会有所帮助:

setValidity("myclass", function(object){
  if(length(slot(object, "id")) == 0L){
    return("You cannot do that")
  }
  return(TRUE)
})

> new("myclass")
An object of class "myclass"
Slot "id":
character(0)

但不幸的是,空参数似乎会导致验证函数被绕过。有没有办法使这种类型的输入无效?

我能找到的最佳解决方案是将验证步骤放在构造函数中(这对我来说似乎有点反常):

setMethod("initialize", "myclass", function(.Object, id){
  if(missing(id)) stop("The id is not allowed to be empty")
  .Object@id <- id
  validObject(.Object)
  return(.Object)
})

这现在给出了预期的结果:

> new("myclass")
Error in .local(.Object, ...) : The id is not allowed to be empty
> new("myclass", id = character())
Error in validObject(.Object) : 
  invalid class “myclass” object: You cannot do that
> new("myclass", id = "a")
An object of class "myclass"
Slot "id":
[1] "a"