You can't. cat()
is not a generic function so you can't write methods for it.
You could make new version of cat()
that is generic:
cat <- function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE) {
UseMethod("cat")
}
cat.default <- function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE) {
base::cat(..., file = file, sep = sep, fill = fill, labels = labels,
append = append)
}
But the semantics of dispatching on ...
is not well defined (I couldn't find where, if anywhere, it's documented). It looks like dispatch occurs based only on the first element in ...
:
cat.integer <- function(...) "int"
cat.character <- function(...) "chr"
cat(1L)
#> [1] "int"
cat("a")
#> [1] "chr"
This means that the class of the second and all subsequent arguments is ignored:
cat(1L, "a")
#> [1] "int"
cat("a", 1L)
#> [1] "chr"
If you want to add a foo
method to cat()
, you just need a little extra checking:
cat.foo <- function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE) {
dots <- list(...)
if (length(dots) > 1) {
stop("Can only cat one foo at a time")
}
foo <- dots[[1]]
cat(foo$one, foo$two, file = file, sep = sep, fill = fill, labels = labels,
append = append)
cat("\n")
}
foo <- structure(list(one=1,two=2), class = "foo")
cat(foo)
#> 1 2