2

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?

Daniel Krizian
  • 4,586
  • 4
  • 38
  • 75

1 Answers1

1

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.

Community
  • 1
  • 1
xb.
  • 1,617
  • 11
  • 16
  • You are very welcome! Actually, I would have not asked that question linked above if I saw your post first! Because the code in your "question" is almost the "answer" for that question! So I voted you up :) – xb. Feb 07 '14 at 23:04
  • haha, nice synergies there :) let's keep up exploring the big picture via tiny examples interspersed here and there! – Daniel Krizian Feb 08 '14 at 23:41