I have this code:
class MyLinkedList[T](h: T, tail: MyLinkedList[T]) {
def prepend(v: T): MyLinkedList[T] = new MyLinkedList(v, this)
}
I wonder how it comes that I can pass the second parameter as null and it works:
val l: MyLinkedList[Int] = new MyLinkedList(1, null)
null is an instance of MyLinkedList[Int]?? It seems no:
println(null.isInstanceOf[MyLinkedList[Int]])
outputs false.
So why?
nullis something supported by Scala for reverse compatibility with other languages that run on the JVM and .NET framework. The language designers aren’t particularly thrilled about it but yes, it compiles just like Java code. You should never use it in native Scala situations. Scala provides alternatives, most idiomatically, such asOptionwith instancesSomeandNonewhich is essentially aNullablewrapper, for when you do need to allow a null option.