Skip to contents

Creates an enumerated type with a fixed set of possible values. This function returns an enum generator, which can be used to create enum objects with values restricted to the specified set.

Usage

enum(...)

Arguments

...

The possible values for the enumerated type. These should be unique character strings.

Value

A function (enum generator) of class 'enum_generator' that creates enum objects of the defined type. The returned function takes a single argument and returns an object of class 'enum'.

See also

interface for using enums in interfaces

Examples

# Create an enum type for colors
Colors <- enum("red", "green", "blue")

# Create enum objects
my_color <- Colors("red")
print(my_color)  # Output: Enum: red
#> Enum: red 

# Trying to create an enum with an invalid value will raise an error
try(Colors("yellow"))
#> Error in Colors("yellow") : 
#>   Invalid value. Must be one of: red, green, blue

# Enums can be used in interfaces
ColoredShape <- interface(
  shape = character,
  color = Colors
)

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

# Modifying enum values
my_shape$color$value <- "blue"  # This is valid
try(my_shape$color$value <- "yellow")  # This will raise an error
#> Error in `$<-.enum`(`*tmp*`, value, value = "yellow") : 
#>   Invalid value. Must be one of: red, green, blue