Calculated field with delayed evaluation in a `ReferenceClass`

80 views Asked by At

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?

1

There are 1 answers

2
xb. On BEST ANSWER

It is evident that the value is evaluated until it is referenced. See

Auto 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.