Under what conditions is anything desirable displayed?

In my own code and in numerous mailing lists, I noticed confusion over the fact that Nothing was not inferred as the upper bound of two other types.

The answer may be obvious to you *, but I'm lazy, so I ask you:

  • Under what conditions can Nothing be the most desired result?

  • Would it be reasonable for the compiler to give an error in these cases, or a warning if it is not overridden by some kind of annotation?

* Multiple

+6
scala type-inference nothing
source share
2 answers

It is not possible to infer Nothing smallest upper bound of two types unless these two types are also Nothing . When you inferred the smallest upper bound of the two types, and the two types have nothing in common, you get Any (in most cases you get AnyRef , though, because you only get Any when the value type is involved, like Int or Long .)

+2
source share

Nothing is a subtype of everything, so in a sense it is the counting part of Any, which is a supertype of everything. Nothing can be created; you will never hold a Nothing object. There are two situations (I know) where Nothing is really useful:

  • A function that never returns (as opposed to a function that does not return a useful value that Unit would use instead), which occurs for infinite loops, infinite locking, always throwing an exception or exiting the application
  • As a way to specify the type of empty containers, for example. Neal or not. In Java, you cannot have a single Nil object for universal immutable lists without casting or other tricks. If you want to create a list of dates, even an empty element must have the correct type, which must be a subtype of Date. As a date and, for example, Integer does not use a common subtype in Java, you cannot create such an instance of Nil without tricks, even though your Nil does not even matter. Now Scala has this common subtype for all objects, so you can define Nil as an object Nil extends List[Nothing] , and you can use it to start any list that you like.

To your second question: Yes, that would be helpful. I would suggest that there is already a compiler to enable these warnings, but I'm not sure.

+4
source share

All Articles