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?
You can get an error because when you define your Player
class, you set the possession
field to have type Ball
. But in your pass
function, you set possession
to be NULL:
possession <<- NULL
If you change the initialisation to:
p = setRefClass('Player', fields = list(name = 'character', possession = 'ANY')
then everything works as expect:
R> p2$receive(p1$pass())
R> p1
Reference class object of class "Player"
Field "name":
[1] "Ronaldinho"
Field "possession":
NULL
R> p2
Reference class object of class "Player"
Field "name":
[1] "Beckham"
Field "possession":
Reference class object of class "Ball"
Field "size":
[1] 5