Lets say I want to make a class “myClass” with two slots A and B.
now I want a validObject function that ensures A and B are the same length
same_length <- function(object){
if(length(object@A)!=length(object@B)) {
"vectors are not the same length"
} else TRUE
}
setClass("myClass", representation(A="numeric", B="numeric"),
validity=same_length)
I saw a function somewhere that will ensure the class is valid when initialized:
setMethod("initialize", "myClass", function(.Object, ...){
value <- callNextMethod()
validObject(value)
value
})
which will send an error if I try
newObj <- new(“myClass”, A=c(1,2,3), B=c(1,2))
But if I do
newObj <- new("myClass")
newObj@A <- c(1,2,3)
newObj@B <- c(1,2)
no error is thrown. How do I get it to throw an error as soon as a new slot assignment does not validate?
Write a ‘replacement method’ that does the check. To do this, we need to create a generic function (because no function with the appropriate name and signature already exists)
We then need to implement the replacement method for the specific types of objects we want to handle — the first argument is of class ‘myClass’, the second argument (
value) is of class ‘numeric’:We might also write a ‘getter’ generic and method
and then
Note that the default
initializemethod callscheckValidity, so if you usecallNextMethodas the last line in your constructor there’s no need to explicitly check validity.