简体   繁体   English

为什么Option的orNull方法有这个多余的隐式参数?

[英]Why does the Option's orNull method have this superfluous implicit argument?

I wonder what is the reason for the (implicit ev: Null <:< A1) here: 我想知道(implicit ev: Null <:< A1)的原因是什么:

sealed abstract class Option[+A] extends Product with Serializable { 
  def orNull[A1 >: A](implicit ev: Null <:< A1): A1 = this getOrElse null
  ...
}

Wouldn't 岂不

def orNull[A]: A = this getOrElse null

be enough considering that it doesn't even seem to work with value types like 考虑到它似乎甚至不适用于像这样的值类型

Option(1).orNull

but

Option(1).getOrElse(null)

does? 呢?

Option 's source code Option源代码

Not all scala types can be null. 并非所有scala类型都可以为null。 In particular, Any has two children, AnyRef and AnyVal. 特别是,Any有两个孩子,AnyRef和AnyVal。 AnyRef can handle null types. AnyRef可以处理null类型。 AnyVal types could be primitives on the JVM and therefore cannot be null. AnyVal类型可以是JVM上的原语,因此不能为null。 The implicit is a delayed type-check that allows Option[String] to use orNull but not Option[Int]. 隐式是一种延迟类型检查,允许Option [String]使用orNull而不是Option [Int]。

Note: This dichotomy of Int being boxed/unboxed object/primitive has very strange manifestations in Scala, such as null.asInstanceOf[Int] == 0 // true. 注意:Int的盒装/非盒装对象/原语的这种二分法在Scala中有非常奇怪的表现形式,例如null.asInstanceOf [Int] == 0 // true。

scala> abstract class Op[A] {
     |   def getOrElse(b: A): A
     |   def orNull[A]: A = this getOrElse null
     | }
<console>:14: error: type mismatch;
 found   : Null(null)
 required: A
         def orNull[A]: A = this getOrElse null
                                           ^

So, null is not an acceptable type for all A , only for the nullable ones. 因此,对于所有Anull不是可接受的类型,仅适用于可空的。 The subclasses of AnyVal are typical examples of non-nullable types. AnyVal的子类是非可空类型的典型示例。 In the absence of that parameter, it is not possible to write this method. 如果没有该参数,则无法编写此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM