Is it possible to create an arbitrary (non-function) callable object?

Is it possible to create a custom callable object in R?

Specifically, I'm interested in creating an object that behaves like a function (can be called with parentheses), but that has additional metadata attached:

To take a simple example:

my_callable <- not_a_function() # ???

#> "Hello world (or something)"

#> "This object does a thing"

I was thinking about possibly subclassing function?

I suspect that this kind of pattern is deeply non-idiomatic; I'm interested in the question primarily from the persepective of understanding the language better.

1 Like

I'm not sure if this will answer your question, but it seemed relevant:


a S3 or S4 object can inherit “function” semantics and become callable

This is perfect!! Exactly what I was looking for. Thank you very much, Mara!

1 Like