Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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
like image 752
Matt R Avatar asked Nov 29 '11 15:11

Matt R


1 Answers

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.

like image 170
Iulian Dragos Avatar answered Sep 22 '22 16:09

Iulian Dragos