Scala Programming – How Is Nothing a Subtype of Every Other Type?

programming-languagesscala

I am taking Martin Odersky's coursera course on functional programming with scala, and for now I have learned two things that together don't make sense:

  1. Scala doesn't support multiple inheritance
  2. Nothing is a subtype of every other type

These two statements cannot live together, so how exactly is this done? and what exactly is the meaning of "subtype of every other type"

Edit 1

In the Scala API, Nothing is defined as abstract final class Nothing extends Any… so how can it extend other classes?

Best Answer

Subtyping and inheritance are two different things! Nothing doesn't extend everything, it's a subtype, it only extends Any.

The specification[§3.5.2] has a special case governing the subtyping-relationship of Nothing:

§3.5.2 Conformance

  • [...]
  • For every value type
    T , scala.Nothing <: T <:scala.Any
  • For every type constructor T (with any number of type parameters)
    scala.Nothing <: T <: scala.Any
  • [...]

Where <: basically means "is a subtype of".

As for how this is done: We don't know, it's compiler magic and an implementation detail.

Quite often a language does things you as a programmer can't. As a counterpart to Nothing: Everything in Scala inherits from Any, everything except Any. Why doesn't Any inherit from something? You can't do that. Why can Scala do that? Well, because Scala set the rules, not you. Nothing being a subtype of everything is just an other instance of this.