Get startedGet started for free

Writing the Next Method

When objects have multiple classes, you may wish to call methods for several of these classes. This is done using NextMethod() (docs).

The S3 methods now take the form:

an_s3_method.some_class <- function(x, ...)
{
  # Act on some_class, then
  NextMethod("an_s3_method")
}

That is, NextMethod() should be the last line of the method.

This exercise is part of the course

Object-Oriented Programming with S3 and R6 in R

View Course

Exercise instructions

The variable kitty, and the generic what_am_i() function have been predefined in your workspace.

  • Inspect your workspace with ls.str().
  • Complete the definition of the cat method for what_am_i().
    • Write a message() (docs) stating "I'm a cat".
    • Call NextMethod() (docs), passing the name of the generic as a string.
  • Define a mammal method for what_am_i().
    • The arguments are the same as for the cat method.
    • Write a message() stating "I'm a mammal".
    • Call NextMethod().
  • Define a character method for what_am_i().
    • The arguments are the same as for the cat method.
    • Write a message() stating "I'm a character vector".
    • Don't call NextMethod().
  • Call what_am_i() with kitty as an input, verifying that all three messages are shown.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Inspect your workspace
ls.str()

# cat method
what_am_i.cat <- function(x, ...)
{
  # Write a message
  ___
  # Call NextMethod
  ___
}

# mammal method
___ <- ___

# character method
___ <- ___

# Call what_am_i()
___
Edit and Run Code