Skip to contents

An interface defines a structure with specified properties and their types or validation functions. This is useful for ensuring that objects adhere to a particular format and type constraints.

Usage

interface(..., validate_on_access = FALSE, extends = list())

Arguments

...

Named arguments defining the properties and their types or validation functions.

validate_on_access

Logical, whether to validate properties on access (default: FALSE).

extends

A list of interfaces that this interface extends.

Value

A function of class 'interface' that creates objects implementing the defined interface. The returned function takes named arguments corresponding to the interface properties and returns an object of class 'interface_object'.

Examples

# Define an interface for a person
Person <- interface(
  name = character,
  age = numeric,
  email = character
)

# Create an object that implements the Person interface
john <- Person(
  name = "John Doe",
  age = 30,
  email = "john@example.com"
)

# Using enum in an interface
Colors <- enum("red", "green", "blue")
ColoredShape <- interface(
  shape = character,
  color = Colors
)

my_shape <- ColoredShape(shape = "circle", color = "red")

# In-place enum declaration
Car <- interface(
  make = character,
  model = character,
  color = enum("red", "green", "blue")
)

my_car <- Car(make = "Toyota", model = "Corolla", color = "red")