foo1 <- new_class("foo1", properties = list(x = class_numeric, y = class_numeric))
foo2 <- new_class("foo2", foo1, properties = list(z = class_numeric))
total <- new_generic("total", "x")
method(total, foo1) <- function(x) x@x + x@y
# This won't work because it'll be stuck in an infinite loop:
method(total, foo2) <- function(x) total(x) + x@z
# We could write
method(total, foo2) <- function(x) x@x + x@y + x@z
# but then we'd need to remember to update it if the implementation
# for total() ever changed.
# So instead we use `super()` to call the method for the parent class:
method(total, foo2) <- function(x) total(super(x, to = foo1)) + x@z
total(foo2(1, 2, 3))
# To see the difference between convert() and super() we need a
# method that calls another generic
bar1 <- new_generic("bar1", "x")
method(bar1, foo1) <- function(x) 1
method(bar1, foo2) <- function(x) 2
bar2 <- new_generic("bar2", "x")
method(bar2, foo1) <- function(x) c(1, bar1(x))
method(bar2, foo2) <- function(x) c(2, bar1(x))
obj <- foo2(1, 2, 3)
bar2(obj)
# convert() affects every generic:
bar2(convert(obj, to = foo1))
# super() only affects the _next_ call to a generic:
bar2(super(obj, to = foo1))
Run the code above in your browser using DataLab