Skip to main content

23  Typed arguments and results

A generic may declare the types of its parameters and of its result. Each call checks and converts its arguments before it dispatches, and checks the method’s result, so a method receives values of the declared types and a caller receives a value of the return type.

23.1 Typed parameters

arg(type, default) in params() gives a parameter its type and, when it is given, its default. Each type constructor has a shorthand with the constructor’s arguments, then default: arg_integer(min = 1L) is arg(type_integer(min = 1L)).

Sample <- new_struct("Sample", fields = list(values = vec(type_double())))

summarize <- generic(
  "summarize",
  params(
    x,
    digits = arg_integer(min = 0L, max = 15L, default = 3L),
    center = arg_character(values = c("mean", "median"), default = "mean"),
    weights = arg_option(vec(type_double(min = 0)))
  )
)

implement(summarize, Sample) <- function(x, digits, center, weights) {
  values <- if (is.null(weights)) x$values else x$values * weights
  round(if (center == "mean") mean(values) else median(values), digits)
}

heights <- Sample(values = c(1.234, 2.345, 9.876))
summarize(heights)
[1] 4.485
summarize(heights, digits = 1, center = "median")
[1] 2.3

digits = 1 is a double. It converts to the integer 1L, as it does in a constructor. A parameter without a default is required. arg_option(type) has the default NULL, so the argument may be omitted; arg(option(type)) is required and may be NULL.

23.2 Errors

A call reports every problem of every argument in one error, of class r8_argument_error:

summarize(heights, digits = -1L, center = "mode")
Error:
! Invalid arguments of `summarize()`: 2 problems
- `digits` must be at least 0; found -1. [below_min]
- `center` must be one of "mean" or "median"; found "mode". [not_in_values]

A default that does not satisfy its type is named by its expression:

first <- generic(
  "first",
  params(x, n = arg_integer(min = 1L, default = length(x$values)))
)

implement(first, Sample) <- function(x, n) {
  Sample(values = x$values[seq_len(n)])
}
first(Sample(values = numeric()))
Error:
! Invalid arguments of `first()`: 1 problem
- `n`, its default `length(x$values)`, must be at least 1; found 0. [below_min]

A constant default is checked at the declaration:

generic("last", params(x, n = arg_integer(min = 1L, default = 0L)))
Error:
! the default of `n` is invalid: The value must be at least 1; found 0. [default_invalid at /params/1/default]

A missing argument without a default, and an error raised while an argument is evaluated, are R’s own errors. Typed arguments are evaluated in the order of the parameters, before the method is chosen; an argument without a type is evaluated when the method uses it.

23.3 Rules over parameters

rules hold over the typed parameters, which a rule reads by name. Each call checks them once every argument satisfies its type, before the method is chosen:

crop <- generic(
  "crop",
  params(x, from = arg_double(), to = arg_double()),
  rules = list(order = rule(from <= to, message = "from is at most to."))
)

implement(crop, Sample) <- function(x, from, to) {
  Sample(values = x$values[x$values >= from & x$values <= to])
}

crop(heights, from = 2, to = 10)$values
[1] 2.345 9.876
crop(heights, from = 10, to = 2)
Error:
! Invalid arguments of `crop()`: 1 problem
- Rule order: from is at most to. [rule_violation]
  from <= to; found from = 10, to = 2

trait_method() takes rules in the same way.

23.4 R8 types and classes

A type means the same in a parameter as in a field. With Window a struct that extends Interval, arg(Interval) admits an Interval only, arg(subtype(Interval)) admits both, arg(dyn(Trait)) any implementor of a trait, and arg(host_class("data.frame")) an object of that class:

clamp <- generic("clamp", params(x, to = arg(subtype(Interval))))

implement(clamp, Sample) <- function(x, to) {
  Sample(values = pmin(pmax(x$values, to$lo), to$hi))
}

clamp(heights, to = Window(lo = 2, hi = 5, label = "usual"))$values
[1] 2.000 2.345 5.000
clamp(heights, to = c(2, 5))
Error:
! Invalid arguments of `clamp()`: 1 problem
- `to` must be a value of `demo::Interval` or of a struct that extends it; found a numeric vector. [not_subtype]

A dispatched parameter may have a type that names its values’ types: an R8 type, subtype(), dyn(), or host_class():

width <- generic("width", params(x = arg(subtype(Interval))))

implement(width, Interval) <- function(x) x$hi - x$lo

width(Window(lo = 0, hi = 2, label = "first"))
[1] 2

A method for a type outside it is a declaration error:

implement(width, Sample) <- function(x) diff(range(x$values))
Error:
! Declaration of `impl demo::width for demo::Sample` failed:
- the parameter `x` of `demo::width@width` admits no value of demo::Sample [dispatch_param_type at /target]

23.5 Return types

return_type is the type of the value that every method returns. A method may declare a type of its own that fits it, such as a struct that extends the declared one:

Model <- new_struct("Model", fields = list(error = type_double(min = 0)))
MeanModel <- new_struct("MeanModel", fields = list(mean = type_double()), extends = Model)

fit <- generic("fit", params(x), return_type = subtype(Model))

implement(fit, Sample, return_type = MeanModel) <- function(x) {
  MeanModel(error = var(x$values), mean = mean(x$values))
}

fit(heights)
<demo::MeanModel>
  error: 22.10574
  mean: 4.485
fit
<r8 generic demo::fit>
fit(x)
  returns subtype of demo::Model
Methods for: demo::Sample (returns demo::MeanModel)

A result that does not satisfy the method’s type, or the generic’s for a method without one, raises r8_result_error, which names the method:

implement(fit, Interval) <- function(x) x$hi
fit(Interval(lo = 0, hi = 1))
Error:
! Invalid result of `fit()` from its method for `demo::Interval`: 1 problem
- The value must be a value of `demo::Model` or of a struct that extends it; found a numeric vector. [not_subtype]

return_type = "Self" is the type of the first dispatched argument, as for a replacement generic, so a method for a parent returns the child for a child’s value. A result converts as an argument does, and an invisible result stays invisible.

23.6 The contract of a call

The checks belong to the generic’s call. r8method() returns a method that checks nothing, and r8next_impl() calls the next method without checking its arguments or its result. A trait method that is an existing S3 generic, such as summary, declares names only, since R calls it without R8.

In the declaration that other languages read, a constant default is a value that any host uses, and any other default is an R expression: a call from R may omit the argument, and a call from another host supplies it.

23.7 Cost

A call of a generic without types is unchanged. The table gives the time that the checks add to a call, in nanoseconds, against the same checks in a function (bench/typed.R in the R8 repository; R 4.6.2, Apple M5, 2026-11-23; minimum of 11 rounds):

Check R8 Hand-written checkmate 2.3.4
An integer and a double 199 380 1,157 (qassert()), 2,638 (assert_*())
A struct 161 89 (inherits()) 2,931 (assert_class())
subtype() or dyn() 158
10^6 doubles of at least 0 561,171 2,152,097 705,600 (assert_numeric())
A result, one double 330 160 1,079 (assert_number())
© 2026 E.D. Gennatas