Skip to contents

This method should allow any S3 object in R to become immutable by intercepting [<-, [[<-, $<- and c during S3-method dispatch and returning an error.

Reverse with call to the mutable function.

Usage

immutable(object)

is.immutable(object)

# S3 method for immutable
print(x, ...)

show.immutable(x)

Arguments

object, x

Any R object which uses S3 method dispatch

...

Fallthrough arguments to print.default.

Value

The object with "immutable" prepended to its class attribute.

logical(1) Does the object inherit from the "immutable" S3-class?

None, invisible(NULL)

Details

The motivation for this class was to create pseudo-private slots in an R S4 object by preventing mutation of those slots outside of the accessors written for the class. It should behave as expected for R object which operate with 'copy-on-modify' semantics, including most base R functions and S3 objects.

An environment was not suitable for this case due to the 'copy-by-reference' semantics, such that normal R assignment, which users assume makes a copy of the object, actually references the same environment in both the original and copy of the object.

WARNING: This implementation is unable to intercept modifications to a data.table via the set* group of methods. This is because these methods are not S3 generics and therefore no mechanism exists for hooking into them to extend their functionality. In general, this helper class will only work for objects with an S3 interface.

Examples

immutable_list <- immutable(as.list(1:5))
class(immutable_list)
#> [1] "immutable"
# errors during assignment operations
tryCatch({ immutable_list$new <- 1 }, error=print)
#> <simpleError: Object is immutable! Use `mutable(object)` to return a mutable copy.>

immutable_list <- immutable(as.list(1:5))
is.immutable(immutable_list)
#> [1] TRUE