请说明Option的orNull方法的使用

请说明Option的orNull方法的使用

本文介绍了请说明Option的orNull方法的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 的 Option 类有一个 orNull 方法,其签名如下所示.

Scala's Option class has an orNull method, whose signature is shown below.

orNull [A1 >: A](implicit ev : <:<[Null, A1]) : A1

我对隐含的东西感到困惑.有人可以解释一下如何使用它,最好是一个例子吗?

I'm bewildered by the implicit thing. Would somebody please explain how it can be used, ideally with an example?

推荐答案

scala> Some(1).orNull
<console>:10: error: could not find implicit value for parameter ev: <:<[Null,Int]
       Some(1).orNull
               ^
scala> (None : Option[Int]).orNull
<console>:10: error: could not find implicit value for parameter ev: <:<[Null,Int]
       (None : Option[Int]).orNull

scala> Some("hi").orNull
res21: java.lang.String = hi

scala> Some(null : String).orNull
res22: String = null

scala> (None : Option[String]).orNull
res23: String = null

解释隐含的东西:orNull 是一种从 Some|None 习语回到 Java 的 value|null 习语(当然,这是不好的)的方法.现在只有 AnyRef 值(类的实例)可以接受空值.

To explain the implicit thing: orNull is a way of getting back from the Some|None idiom to Java's value|null idiom (which is, of course, bad). Now only AnyRef values (instances of classes) can accept a null value.

所以我们想要的是 def orNull[A >: Null] = .....但是 A 已经设置了,我们不想在特征的定义中限制它.因此, orNull 需要 A 是可空类型的证据.该证据采用隐式变量的形式(因此命名为ev")

So what we would have liked is def orNull[A >: Null] = ..... But A is already set and we don't want to restrict it in the definition of the trait. Therefore, orNull expects an evidence that A is a nullable type. This evidence is in the form of an implicit variable (hence the name 'ev')

<:<[Null, A1] 可以写成 Null <:<A1 这么看,类似于'Null conforms 的隐式值的方法中定义.

<:<[Null, A1] can be written as Null <:< A1 seeing it like this, it is similar to 'Null <: A1'. <:< is defined in Predef as well as the method that provides the implicit value named conforms.

我认为这里并不严格要求使用 A1,因为 orNull 使用 getOrElse(其中默认值可以是 A 的超类型)

I think the use of A1 is not strictly required here and is because orNull uses getOrElse (where the default given can be a super type of A)

scala> class Wrapper[A](option: Option[A]) {
     | def orNull(implicit ev: Null <:< A): A = if(option.isEmpty) null else option.get
     | }
defined class Wrapper

scala> new Wrapper(Some("hi")).orNull
res18: java.lang.String = hi

这篇关于请说明Option的orNull方法的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:45