I am trying to "pass" a reference to an Reference Class object (say, a ball) between two other Reference Class objects (say, two soccer [football] players) with the following example:
# create Reference classes
b <- setRefClass('Ball', fields = list(size = 'numeric'))
p <- setRefClass('Player', fields = list(name = 'character', possession = 'Ball'),
methods = list(pass = function(){
tmp <- possession$copy()
possession <<- NULL
return(tmp)
}, receive = function(newBall){
possession <<- newBall
}
))
# initialize pretend all-star team
# p1 gets initial possession of a new ball
p1 <- p$new(name = 'Ronaldinho', possession = b$new(size=5) )
p2 <- p$new(name = 'Beckham')
# now pass the ball from p1 to p2
p2$receive(p1$pass())
However I get the following error:
Error in function (value) :
invalid replacement for field ‘possession’, should be from class “Ball” or a subclass (was class “NULL”)
Theoretically I am trying to retutn a reference to the ball object, and then add that reference to the other player, but obviously that is not working. I know it is possible to achieve the same results by accessing the fields directly, but I would like to find a way to accomplish this "pass" using internal methods of the class only. Is this possible? Why am I getting this error?