rogue-one
rogue-one

Reputation: 11587

Scala: Null and Nothing

It is said that scala.Nothing and scala.Null are bottom classes and they extend every other AnyRef classes. consider the below snippet

class Test() {}
val test:Test = null

So for the statement to succeeded either Null should extend the custom class Test (i.e. Test is a super type of Null) or the type system should make exceptions of not throwing type mismatch error for scala.Null. How scala ensures that these two classes always extend any other AnyRef descendants classes in scala ?

Upvotes: 3

Views: 369

Answers (1)

dmitry
dmitry

Reputation: 5039

Typically compiler explicitly handles bottom type conformity, like in the excerpt from scala compiler:

...
} else if (isNullType) {
  if (other.isNothingType) false
  else if (other.isPrimitive) false
  else true // Null conforms to all classes (except Nothing) and arrays.
} else if (isNothingType) {
  true
} else other match {
...

Upvotes: 3

Related Questions