[R] S4: When is validObject issued? (or why S4 is killing me:( ..

Vitalie S. vitosmail at rambler.ru
Fri Jun 5 21:44:43 CEST 2009


Dear UseRs,

Does anyone know when exactly the validity is checked in S4? Documentation is silent:(. 

Here is a small example:

 setClass("test1",representation(a="numeric"))
 setMethod("initialize","test1",
           function(.Object,...){
		a<-runif(1)  ## here  slot "a" is initialized ##
                callNextMethod(.Object,a=a,...) 
           })

> new("test1")
An object of class "test1"
Slot "a":
[1] 0.755

#next new subclass is created with an additional slot "b":
 setClass("test2",contains="test1",representation(b="numeric")
          ## validity to test a==b ##   
          ,validity=function(object){
              if(object at a!=object at b) print("values must be equal!!")
              else TRUE
          })

 setMethod("initialize","test2",
           function(.Object,...){
               .Object<-callNextMethod(.Object,...)
               .Object at b<-.Object at a   ## here "b" is initialized ##
               .Object
           })

> new("test2")
Error in if (object at a != object at b) print("values must be equal!!") else TRUE : 
  argument is of length zero

This could mean only one thing, validity of "test2" is checked before it gets to point when b is initialized (i.e. in callNextMethod). But this is absurd (at leas from my point): callNextMethod constructs object of type "test" and should have nothing to do with validity of "test2". 
Shouldn't validity be checked only after the object is created?

Second my slot "a" is initialized in "test1"'s constructor and "b" must be assigned only after the callNextMethod as in above code. Seemingly unsolvable paradox? How to be?

Many thanks.




More information about the R-help mailing list