Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

scala - Difference in flattening an Option[List[Int]] in 2.9.1 and 2.10 nightly

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)

Versus:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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).

Here's the signature of flatten in 2.10:

def flatten[B](implicit ev: <:<[A, Option[B]): Option[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].

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...