我有这个代码:
class MyLinkedList[T](h: T, tail: MyLinkedList[T]) {
def prepend(v: T): MyLinkedList[T] = new MyLinkedList(v, this)
}
我想知道我如何可以将第二个参数作为 null 传递并且它可以工作:
val l: MyLinkedList[Int] = new MyLinkedList(1, null)
null
是 MyLinkedList[Int] 的实例?看来没有:
println(null.isInstanceOf[MyLinkedList[Int]])
outputs false
.
So why?
这篇博文 http://oldfashionedsoftware.com/2008/08/20/a-post-about-nothing/很好地解释了null
在 Scala 中(连同Null http://www.scala-lang.org/api/current/index.html#scala.Null, Nil http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Nil%24, Nothing http://www.scala-lang.org/api/current/index.html#scala.Nothing and None http://www.scala-lang.org/api/current/index.html#scala.None%24):
Null
是一个特征,它(如果你不熟悉特征)有点像 Java 中的抽象类。恰好存在一个实例Null
, 那就是null
。没那么难。字面意思null
与 Java 中的用途相同。它是不引用任何对象的引用的值。因此,如果您编写一个采用类型参数的方法Null
,你只能传入两件事:null
本身或类型的引用Null
.
Thus null
不是 Scala 类型系统中除以下类型之外的任何类型的实例Null
:
scala> null.isInstanceOf[Any]
res1: Boolean = false
好的,所以它必须是一个实例Null
那么,对吧?出色地...
scala> null.isInstanceOf[Null]
<console>:8: error: type Null cannot be used in a type pattern or isInstanceOf test
null.isInstanceOf[Null]
总的来说,正如其他人指出的那样,Null
and null
存在只是为了向后兼容 Java。否则,Null
与以下状态相同Nothing
,但后者没有实例,它是 Scala 类型系统中更有机的一部分,因为它在特定的使用场景中具有明确的角色,例如定义空集合,或者从函数调用中异常退出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)