views:

127

answers:

2

In my own code, and on numerous mailing list postings, I've noticed 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

+4  A: 

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.

Landei
Thanks, but I'm well aware of what Nothing is good for, in isolation; I'm trying to figure out when it's useful for it to be inferred by the LUB algorithm.
Alex Cruise
+2  A: 

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.)

Ken Bloom