我试图通过以下示例在其他两个参考类对象(例如,两个足球 [football] 球员)之间“传递”对参考类对象(例如球)的引用:
# 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())
但是我收到以下错误:
Error in function (value) :
invalid replacement for field ‘possession’, should be from class “Ball” or a subclass (was class “NULL”)
从理论上讲,我试图重新引用对球对象的引用,然后将该引用添加到其他玩家,但显然这不起作用。我知道可以通过直接访问字段来获得相同的结果,但我想找到一种方法来仅使用类的内部方法来完成此“通过”。这可能吗?为什么我会收到此错误?