When using R6 classes, what is the proper way to define methods outside of the class that call other methods?
Consider the following example, where the function func
might dispatch to another function if it is being used interactively. But, if it does so, the other function doesn't have access to the private environment. Should I be passing an environment around if I define classes this way?
## General function defined outside R6 class
func <- function(x) {
if (missing(x) && interactive()) {
ifunc()
} else {
private$a <- x * x
}
}
## If interactive, redirect to this function
ifunc <- function() {
f <- switch(menu(c('*', '+')), '1'=`*`, '2'=`+`)
private$a <- f(private$a, private$a)
}
## R6 test object
Obj <- R6::R6Class("Obj",
public=list(
initialize=function(a) private$a <- a,
geta=function() private$a,
func=func # defined in another file
),
private=list(
a=NA
)
)
## Testing
tst <- Obj$new(5)
tst$func(3)
tst$geta() # so func sees 'private'
# [1] 9
tst$func() # doesn't see 'private'
Error in ifunc() (from #3) : object 'private' not found