Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If the Nothing type is at the bottom of the class hierarchy, why can I not call any conceivable method on it?

The scala type Nothing represents (as I understand it) the bottom of the type hierarchy, also denoted by the symbol ⊥. That is, Nothing is a sub-type of any given type. The requirement for a Nothing type is explained well by James Iry for those of us without a theoretical background in type theory!

So my question is, if Nothing is a subtype of every type, why can I not call any type's methods on Nothing? Obviously, I cannot instantiate Nothing but why doesn't the following compile?

var n: Nothing = _

def main(args: Array[String]) {
  println(n.length) //compile error: value length is not a member of Nothing
}

Surely as Nothing is a subtype of String this should be OK? Note that the following compiles just fine!

var n: Nothing = _

def foo(s: String) : Int =  s.length

def main(args: Array[String]) {
  println(foo(n))
}

as does:

def main(args: Array[String]) {
  println(n.asInstanceOf[String].length) 
}
like image 799
oxbow_lakes Avatar asked Nov 13 '09 11:11

oxbow_lakes


People also ask

Which is the supertype of all types that refer to objects in Scala?

Scala Type Hierarchy Any is the supertype of all types, also called the top type. It defines certain universal methods such as equals , hashCode , and toString .

Which is a subclass of all classes Scala?

Any has two direct subclasses: AnyVal. AnyRef.


1 Answers

While Nothing is a subtype of everything, it does not inherit any method except for those in Any. This is because Nothing is more geared toward the functional end of the language. It's necessary for things like Option and List, but only as a type, not as a class.

The distinction here is a bit weird for those coming from an object-oriented background, but the fact is that subtyping as a concept is very distinct from OOP. Granted, object-oriented really implies subtyping in some form, but the reverse is not true. Benjamin Pierce's Types and Programming Languages does a good job of presenting the language F_< (pronounced "F sub"), which serves as a minimal example of a language with subtyping (but not OO).

Now, with all that said, I do agree that the fact that Nothing is immune from the normal inheritance rules does seem a bit inconsistent. However, from a theoretical standpoint, it makes perfect sense.

like image 104
Daniel Spiewak Avatar answered Sep 28 '22 17:09

Daniel Spiewak