Under what conditions is inferring Nothing desirable?
In my own code, and on numerous mailing list postings, I've notic开发者_JS百科ed confusion due to Nothing being inferred as the least upper bound of two other types.
The answer may be obvious to you*, but I'm lazy, so I'm asking you*:
Under what conditions is inferring Nothing in this way the most desirable outcome?
Would it make sense to have the compiler throw an error in these cases, or a warning unless overridden by some kind of annotation?
* Plural
Nothing is the subtype of everything, so it is in a certain sense the counter part of Any, which is the super-type of everything. Nothing can't be instantiated, you'll never hold a Nothing object. There are two situations (I'm aware of) where Nothing is actually useful:
- A function that never returns (in contrast to a function that returns no useful value, which would use Unit instead), which happens for infinite loops, infinite blocking, throwing always an exception or exiting the application
- As a way to specify the type of empty Containers, e.g. Nil or None. In Java, you can't have a single Nil object for an generic immutable lists without casting or other tricks: If you want to create a List of Dates, even the empty element needs to have the right type, which must be a subtype of Date. As Date and e.g. Integer don't share a common subtype in Java, you can't create such a Nil instance without tricks, despite the fact that your Nil doesn't even hold any value. Now Scala has this common subtype for all objects, so you can define Nil as
object Nil extends List[Nothing]
, and you can use it to start any List you like.
To your second question: Yes, that would be useful. I'd guess there is already a compiler switch for turning on these warnings, but I'm not sure.
It's impossible to infer Nothing
as the least upper bound of two types unless those two types are also both Nothing
. When you infer the least upper bound of two types, and those two types have nothing in common, you'll get Any
(In most such cases, you'll get AnyRef
though, because you'll only get Any
when a value type like Int
or Long
is involved.)
精彩评论