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

问题描述

限时删除!!

SomeOption 有什么区别?

scala> Some(true)
res2: Some[Boolean] = Some(true)

scala> val x: Option[Boolean] = Some(true)
x: Option[Boolean] = Some(true)

scala> res2 == x
res3: Boolean = true

我看到 Option(null) 返回,而 Some(null) 不会编译:

I see that Option(null) returns, whereas Some(null) won't compile:

scala> val x = Option(null)
x: Option[Null] = None

scala> val x: Option[Boolean] = Some(null)
<console>:7: error: an expression of type Null is ineligible for implicit conversion
       val x: Option[Boolean] = Some(null)
                                     ^

推荐答案

好吧,Some 扩展了 Option,所以它继承了除 get 之外的所有内容和 isEmpty(以及其他一些由 case 类实现的方法).

Well, Some extends Option, so it inherits everything except get and isEmpty (and some other methods implemented by a case class).

Option的伴随对象有一个特殊的apply方法来处理null:

The companion object of Option has a special apply method for dealing with null:

def apply[A](x: A): Option[A] = if (x == null) None else Some(x)

但是 Some.apply 只是为案例类生成的标准 apply 方法.

But Some.apply is just the standard apply method generated for a case class.

Some(null) 在某些情况下编译,但它具有类型 Some[Null](或 Option[Null]),只有在Option的类型参数为引用类型时才能赋值.

Some(null) will compile in some circumstances, but it has type Some[Null] (or Option[Null]), which can only be assigned when the type argument of Option is a reference type.

scala> val a = Some(null)
a: Some[Null] = Some(null)

scala> val b: Option[String] = Some(null)
b: Option[String] = Some(null)

您正在尝试将 Some[Null] 分配给 Option[Boolean],但 Null 不是子Boolean 的类型,因为 Boolean 是一个值类型(底层),不能保存 null 的值.

You're trying to assign a Some[Null] to an Option[Boolean], but a Null is not a sub-type of Boolean, because Boolean is a value type (primitive underneath) and cannot hold a value of null.

这篇关于Scala Some v. Option的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:29