0

I have created a bank account class with the R6 package . It has a balance that is private (not accessible after generation) and methods to withdraw and deposit a certain amount as well as a print method. (Hadley Wickham 14.3.3)

BankAccount <- R6::R6Class("BankAccount", public = list(
  # Functions to withdraw and deposit.
  deposit = function(amount){
    private$balance <- private$balance + amount
  },
  withdraw = function(amount){
    if (amount < private$balance){
    private$balance <- private$balance - amount
    }
    else {
      stop("Amount withdrawn is greater than available balance by", -(private$balance - amount))
    }
  },
  initialize = function(initial_balance){
    private$balance <- initial_balance
  },
  print = function(){
    cat("Bank balance is equal to", private$balance)
  }
  ),
  private = list(
    balance = NULL
  )
)

Currently, if I create a new R6 object and call the withdraw function with an amount greater than its initial balance, the function will stop and print a message. Instead, I would like the newly created object to be directly removed. How can I achieve this?

umbecdl
  • 21
  • 3
  • Why do you want to "remove" the (account?) object, what do you want to achieve? – R Yoda Jan 05 '20 at 16:26
  • It would be nice for simulation purposes, to keep track of the numbers of accounts surviving for example (it is a bit sloppy, but hope you get the point) – umbecdl Jan 05 '20 at 16:51
  • Objects do not "destruct" theirselves but when no no more reference to an object exists the finalizer function is called once the object is garbage collected (which in non-deterministic). So you have to use another method to count the number of accounts that have a positive account value eg. by adding a function `HasPositiveBalance`. How do you maintain the references to all class instances created by `BankAccount$new`. If you have a container object for that (eg. a list or vector) it should be quite easy to count the surviving objects by removing the other ones... – R Yoda Jan 06 '20 at 12:11
  • So please add a minimal client code example to your question to give us a chance to provide good answers. THX :-) – R Yoda Jan 06 '20 at 12:25

0 Answers0