My primary language is statically typed (Java). In Java, you have to return a single type from every method. For example, you can't have a method that conditionally returns a String
or conditionally returns an Integer
. But in JavaScript, for example, this is very possible.
In a statically typed language I get why this is a bad idea. If every method returned Object
(the common parent all classes inherit from) then you and the compiler have no idea what you're dealing with. You'll have to discover all your mistakes at run time.
But in a dynamically typed language, there may not even be a compiler. In a dynamically typed language, it's not obvious to me why a function that returns multiple types is a bad idea. My background in static languages makes me avoid writing such functions, but I fear I'm being close minded about a feature that could make my code cleaner in ways I can't see.
Edit: I'm going to remove my example (until I can think of a better one). I think it's steering people to reply to a point I am not trying to make.
(coerce var 'string)
yields astring
or(concatenate 'string this that the-other-thing)
likewise. I've written things likeThingLoader.getThingById (Class<extends FindableThing> klass, long id)
as well. And, there, I might only return something that subclasses what you asked for:loader.getThingById (SubclassA.class, 14)
might return aSubclassB
that extendsSubclassA
...