Menu
CoddyTech

S3 Inheritance Order

Lesson 39 of 48 in Coddy's R for C# Developers course.

C# classes use declared inheritance, virtual overrides and base calls. R S3 dispatch follows an ordered vector of class names, with NextMethod continuing the chain. This is distinct from a class hierarchy of stored base objects. Test that an augmenting method invokes the next behavior once and combines the result correctly.

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
Console.WriteLine(new Child().Value());
class Base {public virtual int Value()=>3;}
class Child:Base {}

R

sound <- function(x)UseMethod("sound")
sound.soft <- function(x)paste0(NextMethod(),"?")
sound.bell <- function(x)"ring"
x<-structure(list(),class=c("soft","bell"))
cat(sound(x),"\n",sep="")

S3 class order affects the dispatch chain.

challenge icon

Challenge

Easy

Define generic fee(x). Its parcel method returns x$units*2. Its urgent method returns NextMethod()+5. The adapter creates class c("urgent","parcel") when input flag is 1, otherwise class parcel. Input is nonnegative units followed by flag 0 or 1.

Keep the declared public API. The visible locked driver checks it directly as well as printing solve(lines). Inputs satisfy the stated contract; all arithmetic is small and finite.

Your code goes in Parcel.R and Exercise.R. main.R sources dependencies in order and holds the supplied input/output code; it cannot be edited.

Try it yourself

source("Parcel.R")
source("Exercise.R")
stopifnot(identical(fee(structure(list(units=7),class=c("urgent","parcel"))),19),identical(fee(structure(list(units=7),class="parcel")),14))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for C# Developers

Practice on your own: Online R compiler