Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Null and Nothing

Tags:

types

scala

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 ?

like image 431
rogue-one Avatar asked Feb 23 '26 05:02

rogue-one


1 Answers

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 {
...
like image 173
dmitry Avatar answered Feb 25 '26 20:02

dmitry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!