Reputation: 23104
I am trying to make R to invoke NextMethod when there is a next-class:
e = new.env()
class(e) = c(class(e), "c11", "c22")
print.c11 = function(e, ...) {
print(e$x);
tryCatch({
NextMethod()
}, warning = function(w) {
}, error = function(e) {
}, finally = {
})
}
print.c22 = function(e, ...) {
print(e$y)
tryCatch({
NextMethod()
}, warning = function(w) {
}, error = function(e) {
}, finally = {
})
}
e$x = 111
e$y = 222
print(e)
This is a dirty hack which will cover all errors and warnings that the method might produce. How can this be done properly?
The above code kind of works without the tryCatch block, that's because, I think, the print.default function was invoked. Now take an example (modified) out of Hadley's advanced R book:
> baz <- function(x) UseMethod("baz", x)
> baz.c <- function(x) c("c", NextMethod())
> baz.d <- function(x) c("d", NextMethod())
> c <- structure(1, class = c("c", "d"))
> baz(c)
Show Traceback
Rerun with Debug
Error in NextMethod() : no method to invoke
Ideally the NextMethod function should return NULL if there is no next class.
Upvotes: 1
Views: 436
Reputation: 46856
Implement a default method, e.g.,
baz.default <- function(x) NULL
and
> c <- structure(1, class = c("c", "d"))
> baz(c)
[1] "c" "d"
Upvotes: 5