I have a question about the Reference Classes. How can I check the field assignments.
Here my sample code:
rm(list=ls(all=TRUE))
setRefClass(
Class = "A",
fields = list(firstValue = "numeric"),
methods = list(
initialize = function(..., firstValue = numeric()) {
setFirstValue(firstValue)
},
getFirstValue = function() {
return(firstValue)
},
setFirstValue = function(value) {
if(length(value) != 0) {
if(value > 10) {
cat("only values lower 10 allowed!\n")
firstValue <<- 10
} else {
firstValue <<- value
}
} else {
firstValue <<- 0
}
}
)
)
test <- getRefClass("A")$new()
test$getFirstValue()
test$firstValue
test$setFirstValue(11)
test$firstValue
test$firstValue <- 11
test$firstValue
My problem is how can I prevent it, that "test$firstValue <- 11" is set without to check the value. In S4, I would solve it like this:
setGeneric(name = 'setFirstValue<-', def = function(object, value) {standardGeneric('setFirstValue<-')})
setReplaceMethod(
f = 'setFirstValue',
signature = 'A',
definition = function(object, value) {
object@.firstValue <- value
validObject(object)
return(object)
}
)
and
setReplaceMethod(
f = "[",
signature = "A",
definition = function(x, i ,j , value) {
if(i == 'firstValue ' || i == 1) {setFirstValue(x) <- value}
return(x)
}
)
Finally, in the class definition of "A" the "validity = function(object){ ... }
" would be placed. But how I can resolve this with Reference Classes?
Thanks for help.