Using R6, how do I find classes and objects that inherit from some superclass?

Viewed 1085

Suppose I have:

Foo <- R6::R6Class("Foo")
Bar1 <- R6::R6Class("Bar1", inherit = "Foo")
Bar2 <- R6::R6Class("Bar2", inherit = "Foo")

f <- Foo$new()

A. Can I do something like

R6::findChildren("Foo")
[1] "Bar1" "Bar2"

(I think this the same as R, R6, Get Full Class Name from R6Generator Object, but including it to be comprehensive)

B. Can I do something like

R6::findInstances("Foo")
[1] "f"

C. Can I do something like

b1 <- Bar1$new()
b2 <- Bar2$new()
R6::findInstances("Foo")
[1] "f" "b1" "b2"
2 Answers

I think that this helper function does what you're looking for:

findR6_obj <- function(className=NULL){
    classList <- eapply(.GlobalEnv, class)
    obj_R6 <- classList[vapply(classList, function(ele) "R6" %in% unlist(ele), logical(1))]
    if (is.null(className)) {
        return(obj_R6)
    } else {
        names(obj_R6[vapply(obj_R6, function(ele) className %in% unlist(ele), logical(1))])
    }
}

If you use it without an argument, it'll return all R6 objects in the global environment (along with some more information about their class), and if you use it with an argument for className, say Foo, it'll return those R6 classes that include Foo.

You could modify this so that it only looks in some specific environment.

Related