"Nothing is a subclass of every other class", how to understand it?
These days I am reading the book "Programming in scala". The book has one sentence in the first paragraph:
For example, just as Any is a superclass of any other class, Nothing is a subclass of every other class.
I understand the first part because every class inherits Any directly or indirectly. But I cannot understand the last part of the sentence.
This is the definition of the Nothing class:
abstract final class Nothing extends Any
source to share
Conceptually, Nothing
this is something that is more difficult to understand than what Any
we are familiar with Java and most other object-oriented programs. Nothing
is Scalas lower type . The definition from Wikipedia says:
In subtyping systems, the bottom type is a subtype of all types. (However, the converse is not true - the subtype of all types is not necessarily the lower type.) It is used to represent the return type of a function that does not return a value : for example, one that loops forever, signals an exception, or exits.
I think the easiest way to think about it is to think of it as a way of describing something that never comes back. You cannot instantiate a type Nothing
yourself. One specific use Nothing
in Scala is to be able to reason about covariant parametric types:
In Scala, the bottom type is denoted as
Nothing
. In addition, its use for functions that simply throw exceptions or otherwise do not return is typically used for covariant parameterized types. For example, ScalaList
is a covariant type constructor, so itList[Nothing]
is a subtype ofList[A]
all types of A. So, ScalaNil
, an object for marking the end of a list of any type belongs to typeList[Nothing]
.
Being a subtype is not the same as being a subclass. From Subtyping :
Subtyping should not be confused with the concept of (class or object) inheritance from object-oriented languages; subtyping is a relationship between types (interfaces in an object-oriented language), whereas inheritance is a relationship between implementations deriving from the language, allowing new objects to be created from existing ones. A number of object oriented languages ββinvoke subtyping interface inheritance.
This is also denoted in the Scala Specification Section Β§3.5.2 (Matching) as part of the <:
(is subtype of relationship), for both value types and type constructors:
- For each type of values
T
,scala.Nothing <: T <: scala.Any
.- For each type constructor
T
(with any number of type parameters)scala.Nothing <: T <: scala.Any
.
One familiar aspect of subtyping is generic type variance, where it -
denotes contravariance but +
denotes covariance.
source to share