4 ms·
Nothing made this as clear for me as using the Nim language, where functions defined as proc doThing(x: MyObject; value: string) can be called both with
by crooked-v 6y ago
Nothing made this as clear for me as using the Nim language, where functions defined as
proc doThing(x: MyObject; value: string)
can be called both with
doThing(x, y)
and with
x.doThing(y)
where x by itself is 'just' a data object, but is treated transparently by the language as having associated functions, setters, getters, etc as if it were a class (even though they can all also be directly called separately).
It's an approach that I find really elegant and that I wish more languages used in some way.
- mehrdadn 6y agoYou certainly can do that. You can also refer to John Smith as "Mr. Smith", even when he's your dad. Whether it's more natural or more jarring or confusing is another question though...
- comfydragon 6y agoThat's a thing you can also do in Python: class MyObject: def doThing(self, value: str) -> None: # whatever pass obj = MyObject() obj.doThing("value!") MyObject.doThing(obj, "a different value!") The only difference is that doThing is namespaced to the MyObject class.