enforce_types {dataclass}R Documentation

Enforced typing in R [Experimental]

Description

This function allows for simple type enforcement in R inspired by C++ and other compiled languages. There are currently six primitive types which the function handles:

Usage

enforce_types(level = c("error", "warn", "none"))

Arguments

level

Should type failures error, warn, or be skipped (none)?

Details

You can also provide default arguments within the parenthesis of the type. This is shown in the example below. You can provide new arguments as well. The function has knowledge of the function declaration when it runs. Note: types are checked at runtime not when the function is declared.

Examples

foo <- function(
  x = int(1L),
  y = chr("Hello!"),
  z = lgl(TRUE),
  a = dbl(1.1),
  b = tbl(mtcars),
  c = NULL # This argument will not be checked
) {

  # Simply place enforce_types() in your function header!
  dataclass::enforce_types()

  # Function logic ...
}

# This run the function with the type defaults
foo()

# This will check types but for new arguments
foo(2L, "Hi!", FALSE, 1.2, mtcars)

# This would fail because types are incorrect!
# foo(1.1, FALSE, NULL, "Hi", list())

# This function will only warn when there are type failures
bar <- function(x = int(1)) {
  dataclass::enforce_types("warn")
}

[Package dataclass version 1.0.0 Index]