Skip to main content

27  Conversion

A type’s converter, r8converter(Type), is a function that converts a value to the type, and the generic of those conversions. implement(converter, source) <- function(x) ... declares the conversion from a class, such as "character", or from an R8 type object:

as_resampler <- r8converter(Resampler)

implement(as_resampler, "character") <- function(x) {
  if (identical(x, "bootstrap")) {
    return(Resampler@Bootstrap())
  }
  Resampler@KFold(n_resamples = as.integer(sub("^kfold", "", x)))
}

as_resampler("kfold5")
<demo::Resampler@KFold>
  n_resamples: 5
  seed: NULL

A package exports the converter under a name of its choice, such as as_resampler(), and documents it with roxygen2; the roclet r8rd() adds each conversion to the converter’s Rd file (Documentation with roxygen2). The method takes exactly one argument, x.

r8convert(x, Type) is the same conversion. It calls the method for the class of x and checks that the result is a value of Type:

r8convert("bootstrap", Resampler)
<demo::Resampler@Bootstrap>
  n_resamples: 10
  seed: NULL

Type@from(x) is the same conversion again, for a struct type and for an enum type; from is the one variant name R8 reserves:

Resampler@from("kfold3")
<demo::Resampler@KFold>
  n_resamples: 3
  seed: NULL

A value of the type converts to itself, and a class without a conversion is an error:

r8convert(5, Resampler)
Error:
! `demo::Resampler` has no From impl for "double", "numeric".

A method that returns a value of another type is an error.

27.1 In Rust style

Each conversion is an impl of the standard trait From(source), which implement() declares on the converter. The same conversion in Rust style:

impl(
  From("character"),
  Resampler,
  methods = list(
    from = function(x) {
      if (identical(x, "bootstrap")) {
        return(Resampler@Bootstrap())
      }
      Resampler@KFold(n_resamples = as.integer(sub("^kfold", "", x)))
    }
  )
)

implement(r8convert, Type) is an error that names the converter’s form. An impl of From is declared in the namespace of the target type or of an R8 source type, and an R8 source type is registered before the impl.

27.2 Conversion and extends

A value of a struct that extends another converts with the conversion from its own type, or else from its nearest ancestor’s, which receives the child’s value unchanged (Extending a struct). A conversion to a parent is never used for its child: a parent’s value is not a child’s.

27.3 Conversion and construction

A constructor takes each field in its type or in a form R8 converts natively, such as a double holding a whole number for an integer field (Structs). A conversion runs only when r8convert(), Type@from(), or a converter calls it, so a field of type Resampler takes a Resampler value, and as_resampler("kfold5") gives one from text.

© 2026 E.D. Gennatas