15.4 Details on generics and methods

15.4.1 Dictate dispatch via signature

Specify function arguments to be used in determining method.

setGeneric("myGeneric", 
  function(x, ..., verbose = TRUE) standardGeneric("myGeneric"),
  signature = "x"
)
#> [1] "myGeneric"

15.4.2 Define generics

General form:

setMethod("myGeneric", "Person", function(x) {
  # method implementation
})

Example to print object:

setMethod("show", "Person", function(object) {
  cat(is(object)[[1]], "\n",
      "  Name: ", object@name, "\n",
      "  Age:  ", object@age, "\n",
      sep = ""
  )
})
john
#> Person
#>   Name: Jon Smythe
#>   Age:  50

Example to access slot:

setGeneric("name", function(x) standardGeneric("name"))
#> [1] "name"
setMethod("name", "Person", function(x) x@name)

name(john)
#> [1] "Jon Smythe"

This is how end users should access slots.