每晚在 2.9.1 和 2.10 中展平 Option[List[Int]] 的区别 [英] Difference in flattening an Option[List[Int]] in 2.9.1 and 2.10 nightly

查看:32
本文介绍了每晚在 2.9.1 和 2.10 中展平 Option[List[Int]] 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每晚在 2.9.1 和 2.10 中都有不同的行为——发生了什么变化?

I get different behaviour in 2.9.1 and 2.10 nightly -- what changed?

Welcome to Scala version 2.9.1.final (OpenJDK Client VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Some(3) map (x => List(x, -x)) flatten
res0: List[Int] = List(3, -3)

对比:

Welcome to Scala version 2.10.0.r26084-b20111129020255 (OpenJDK Client VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> Some(3) map (x => List(x, -x)) flatten
<console>:8: error: Cannot prove that List[Int] <:< Option[B].
              Some(3) map (x => List(x, -x)) flatten

推荐答案

原因是 Option 在 2.10 中获得了一个 flatten 方法,该方法仅适用于嵌套的 Options.

The reason is that Option acquired a flatten method in 2.10, that works only on nested Options.

在 2.9 中,通过对 Iterable 的隐式转换添加了对 flatten 的调用,结果是一个 Iterable(或其子类型,取决于嵌套值Option 内).

In 2.9, the call to flatten was added by an implicit conversion to Iterable, and the result was an Iterable (or a subtype thereof, depending on the nested value inside Option).

这是 2.10 中 flatten 的签名:

Here's the signature of flatten in 2.10:

def flatten[B](implicit ev: <:<[A, Option[B]): Option[B]

它说:如果你能找到证据表明这个选项中的元素是一个 Option 本身,比如 Option[B],我可以把它展平并返回一个 <代码>选项[B].

It says: if you can find evidence that the element inside this option is an Option itself, say Option[B], I can flatten that and return an Option[B].

只有在没有具有该名称的方法时才会尝试隐式,因此这解释了为什么它不回退到 2.9 方法.

Implicits are only tried if there is no method with that name, so that explains why it doesn't fall back to the 2.9 method.

这篇关于每晚在 2.9.1 和 2.10 中展平 Option[List[Int]] 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆