1

Is it possible to allow "UseMethod" to see class functions defined in other environments? See the below code for an example. I would like the h.logical to be detected too such that h(TRUE) would return "logical".

h <- function(x) {
  UseMethod("h")
}
h.character <- function(x){ "char"}
h.numeric <- function(x) { "num" }


aa = list(h.logical=function(x){"logical"})

attach(aa)

h("a")
h(10)
h(TRUE)

This code now throws an error in the last line: Error in UseMethod("h") : no applicable method for 'h' applied to an object of class "logical"

Solving the issue with this example suffices. If that is not possible, I would appreciate help solving the actual use case in another way.

The use case is as follows: I have a package with functions like h above, then I want to add a class to that function. This works fine just adding the new function to .Globalenv. The problem occurs when I want to test this using testthat as I am not allowed to write to .Globalenv within a test. Adding the new class function to some other environment within the test makes it detectable by methods(), however, UseMethod still does not see it and throws an error. Any ideas?

Can I use something else then UseMethod for this purpose or do some other hack while testing to mimic the actual usage?

Any help or pointers to how to handle this is highly appreciated!

Mark
  • 173
  • 4

0 Answers0