In a stripped-down example, I have an object of Portfolio reference class holding individual asset values within the holdings field. There is additional field value, which is calculated by simply summing the individual values of holdings:
Portfolio <- setRefClass("Portfolio",
fields = list(holdings = "numeric",
value = function(v) {
sum(holdings)
})
)
Immediately after populating holdings slot, it is evident that the value slot gets calculated.
Portfolio$new(holdings =c(1055.43, 345.7))
Reference class object of class "Portfolio"
Field "holdings":
[1] 1055.43 345.70
Field "value":
[1] 1401.13
Question: How to rewrite the definition in order to achieve delayed, on-demand evaluation of value field, only when it's being called directly with Portfolio$value?
It is evident that the
valueis evaluated until it is referenced. SeeAuto update of a field (data member) in R reference class
By default, calling the object has to reference all its fields, thus they are also evaluated.