initialize() - binary assignment - initialization and construction of a copy. Usually it is better (also more informative for the user) to provide an explicit constructor
.A = setClass("A", representation(x="numeric")) A = function(x=numeric(), ...) .A(x=x, ...)
validOjbect() is called by default by the initialization method when object creation includes slot assignment, so there is no need to call it explicitly during your own initialization method (see below); maybe you will have
.A = setClass("A", representation(x="numeric"), prototype=prototype(x=NA_integer_)) setValidity("A", function(object) { if (length( object@x ) != 1L) "'x' must be length 1" else TRUE }) A = function(x=NA_integer_, ...) ## signature is informative -- 'x' is integer(1), not just '...' ## coercion (eg, as.integer(), below) and other set-up new("A", x=as.integer(x), ...)
from
> A() An object of class "A" Slot "x": [1] NA > A(x=1) An object of class "A" Slot "x": [1] 1 > A(x=1:2) Error in validObject(.Object) : invalid class "A" object: 'x' must be length 1
An important caveat is that the validity method is not called when there are no slots initialized by the user, so prototype() must be defined to create a valid object (check this with validObject(new("A")) .
For your question, the credibility function is the right place to "check for other errors." It is very difficult to write the correct initialization method, but something closer to the correct one:
.B = setClass("B", representation(x="numeric", y="numeric"), prototype=prototype(x=NA_integer_, y=NA_real_)) setMethod("initialize", "B", function(.Object, ..., x=.Object@x , y=.Object@y ) {
This weird construction allows initialize() to continue to act like a copy constructor.
> b = new("B", x=1, y=2) # constructor > initialize(b, x=2) # copy-constructor An object of class "B" Slot "x": [1] 2 Slot "y": [1] 2
which is important when inheriting a class. But, as you can see, this is quite complicated - after all, it is very difficult and rarely worth the effort to get initialize() correct.
Note that we did not completely fulfill the initialize() contract,
setClass("C", representation(x="numeric", y="numeric"))
which actually acts as a copy constructor when called with new()
> c = new("C", x=1, y=2) > new("C", c, x=2) An object of class "C" Slot "x": [1] 2 Slot "y": [1] 2
against the copy construct for implementing B
> b = new("B", x=1, y=2) > new("B", b, x=2) An object of class "B" Slot "x": [1] 2 Slot "y": [1] NA