Wenn der Nicht -Typ am Ende der Klassenhierarchie steht, warum kann ich dann keine denkbare Methode nennen?
Frage
Der Skala -Typ Nothing
repräsentiert (so wie ich es verstehe) die Unterseite der Typhierarchie, die auch mit dem Symbol ⊥ bezeichnet wird. Das ist, Nothing
ist ein Untertyp eines bestimmten Typs. Die Anforderung für a Nothing
Typ ist gut erklärt von James Iry Für diejenigen von uns ohne theoretischen Hintergrund in der Typtheorie!
Meine Frage ist also, wenn Nothing
ist ein Subtyp jedes Typs, warum kann ich die Methoden eines Typs nicht aufrufen Nothing
? Offensichtlich kann ich nichts unternehmungsfähig machen, aber warum kompiliert das folgende folgende nicht?
var n: Nothing = _
def main(args: Array[String]) {
println(n.length) //compile error: value length is not a member of Nothing
}
Sicher als Nothing
ist ein Subtyp von String
Das sollte in Ordnung sein? Beachten Sie, dass das folgende Einfach gut zusammenstellt!
var n: Nothing = _
def foo(s: String) : Int = s.length
def main(args: Array[String]) {
println(foo(n))
}
ebenso wie:
def main(args: Array[String]) {
println(n.asInstanceOf[String].length)
}
Lösung
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.
Andere Tipps
I suppose Nothing
could accept any method, and perform a standard operation on all of them (throwing an exception). That wouldn't be very useful, though.
By presenting a compile error, the compiler is warning the programmer that a type he most likely didn't want, Nothing
, got inferred somehow at a certain point in the code.
You can call toString
on Nothing
variable because of it s defintion:
final trait Nothing extends Any
And toString is member of Any
. I think scala compiler treat's Nothing
in type bounds only and treats it like any other trait on all over cases. Letting invoke any method on variable with type of Nothing
will be very strange I think.