Of course I realize all types do have a common ancestor, but what I mean is this:
In dynamically-typed languages, it is a common practice to have 'mixed' return types. A common case is a function which attempts to retrieve data from a database, then returns either an object (initialized with the found data) or FALSE (in the event no data was found).
A little pseudocode to demonstrate just such an anti-pattern:
function getObjectFromDatabase(object_id) {
if(result = db_fetch_object("SELECT * FROM objects WHERE id = %d", object_id) {
return result
} else {
return FALSE
}
}
If data is found for my object id, I get a DB record back as an object. If not, I get a boolean value. Then, of course, it is on me, the client, to handle multiple possible return types.
Is the only way to accomplish this in Scala to find a common ancestor for all possible return types and declare that as the return type in the signature?
// Like so:
def getObjectFromDatabase(objectId: Int): Any = {
val result = dbFetchObject("SELECT * FROM objects WHERE id = %d", object_id)
if(result) {
return result
} else {
return false
}
}
Or is it possible to annotate multiple possible return types?
(Note that I do not hope it is possible to do this, as I would prefer it to be enforced that function return types are as unambiguous as possible. It would come as a relief to me to learn that the language forbids ambiguous return types, which is more the reason I am asking.)