method() takes a generic and class signature and performs method dispatch
to find the corresponding method implementation. This is rarely needed
because you'll usually rely on the the generic to do dispatch for you (via
S7_dispatch()). However, this introspection is useful if you want to see
the implementation of a specific method.
Arguments
- generic
An S7 generic, i.e. the result of
new_generic(). Unlike method<-,method()only works with S7 generics; it does not look up methods registered on S3 or S4 generics.- class, object
Perform introspection either with a
class(processed withas_class()) or a concreteobject. Ifgenericuses multiple dispatch then bothobjectandclassmust be a list of classes/objects.
See also
method_explain() to explain why a specific method was picked.
Examples
# Create a generic and register some methods
bizarro <- new_generic("bizarro", "x")
method(bizarro, class_numeric) <- function(x) rev(x)
method(bizarro, class_factor) <- function(x) {
levels(x) <- rev(levels(x))
x
}
# Printing the generic shows the registered method
bizarro
#> <S7_generic> bizarro(x, ...) with 3 methods:
#> 1: method(bizarro, class_integer)
#> 2: method(bizarro, class_double)
#> 3: method(bizarro, new_S3_class("factor"))
# And you can use method() to inspect specific implementations
method(bizarro, class = class_integer)
#> <S7_method> method(bizarro, class_integer)
#> function (x)
#> rev(x)
#> <environment: 0x559f44a14d18>
method(bizarro, object = 1)
#> <S7_method> method(bizarro, class_double)
#> function (x)
#> rev(x)
#> <environment: 0x559f44a14d18>
method(bizarro, class = class_factor)
#> <S7_method> method(bizarro, new_S3_class("factor"))
#> function (x)
#> {
#> levels(x) <- rev(levels(x))
#> x
#> }
#> <environment: 0x559f44a14d18>
# errors if method not found
try(method(bizarro, class = class_data.frame))
#> Error in method(bizarro, class = class_data.frame) :
#> Can't find method for `bizarro(S3<data.frame>)`.
try(method(bizarro, object = "x"))
#> Error in method(bizarro, object = "x") :
#> Can't find method for `bizarro(<character>)`.