I want to write wrapper over R6Class but it don't work, I've tried multiple things after I've found this question dynamically add function to r6 class instance
So I've tried this, they both don't work:
get <- function(x = list()) {
class <- R6::R6Class(classname = "class")
for (name in names(x)) {
class$set("public", name, function() name)
}
class
}
x <- get(x = list(a = 10, b = 20))$new()
x$a()
# b
x$b()
# b
this is because of the looping with closures the for don't create new scope. So I've tried this:
get <- function(x = list()) {
class <- R6::R6Class(classname = "class")
lapply(names(x), function(name) {
print(name)
class$set("public", name, function() name)
})
class
}
x <- get(x = list(a = 10, b = 10))$new()
x$a()
this will throw error that name is not defined, because this behavior of R6Class that everything is is in eval substitute
, so there is no way to make new function that take scope/environment from where it was called. Or is there a way?
My real issue is that I want to create function wrapper and I want to call:
fn <- function() {
x <- 10
y <- myFunction(public = list(
foo = function(y) {
x + y
}
})
z <- y$new()
z$foo(10)
## I want 20 as result
}
Is there a way to create myFunction
function that will create R6Class? The reason why I want this is because I have component system based on R6Class and want to remove some boilerplate that need to be added to each class so it's easier to use. I don't want to create new class system, I would like to use R6 classes.