'Is is possible to use function overloading in R?
Is it possible to use function overloading in R? I've seen answers to this question from 2013, but the language and its possibilities evolved a lot over time. In my specific case, I'd like the following:
formFeedback <- function(success, message)
formFeedback <- function(feedback_object)
Is this at all possible? If not, what's the best practice? Should I use two different named functions, should I make all parameters optional, or should I force the users to always pass an object and make the other one impossible?
Solution 1:[1]
No, there's no function overloading in R, though there are a few object systems that accomplish similar things. The simplest one is S3: it dispatches based on the class attribute of the first argument (though there are a few cases where it looks at other arguments).
So if your feedback_object
has a class attribute, you could make your first form the default and your second one the method for that class, but you'd have to rename the first argument to match in all methods. The functions would need to have different names, formFeedback.default
and formFeedback.yourclass
.
There's also a more complicated system called S4 that can dispatch on the types of all arguments.
And you can craft your own dispatch if you like (and this is the basis for several other object systems in packages), using whatever method you like to decide which function to call.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user2554330 |