flatMap行为在2.10.0中更改

dhg*_*dhg 10 generics scala scala-2.10

我正在将一些代码从2.9转换为2.10,并遇到意外的编译错误.这是最小的形式:

在2.9.2中,这很好用:

scala> List(1).flatMap(n => Set(1).collect { case w => w })
res0: List[Int] = List(1)
Run Code Online (Sandbox Code Playgroud)

在2.10.0中,我们收到一个错误:

scala> List(1).flatMap(n => Set(1).collect { case w => w })
<console>:8: error: no type parameters for method flatMap: (f: Int => scala.collection.GenTraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[List[Int],B,That])That exist so that it can be applied to arguments (Int => scala.collection.immutable.Set[_ <: Int])
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : Int => scala.collection.immutable.Set[_ <: Int]
 required: Int => scala.collection.GenTraversableOnce[?B]
              List(1).flatMap(n => Set(1).collect { case w => w })
                      ^
<console>:8: error: type mismatch;
 found   : Int => scala.collection.immutable.Set[_ <: Int]
 required: Int => scala.collection.GenTraversableOnce[B]
              List(1).flatMap(n => Set(1).collect { case w => w })
                                ^
<console>:8: error: Cannot construct a collection of type That with elements of type B based on a collection of type List[Int].
              List(1).flatMap(n => Set(1).collect { case w => w })
                             ^
Run Code Online (Sandbox Code Playgroud)

但是如果我明确地将内部结果转换为a List或明确指定泛型类型,它在2.10.0中工作正常flatmap:

scala> List(1).flatMap(n => Set(1).collect { case w => w }.toList)
res1: List[Int] = List(1)
scala> List(1).flatMap[Int, List[Int]](n => Set(1).collect { case w => w })
res2: List[Int] = List(1)
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释2.10的变化是什么导致类型推断在2.9中没有失败?

编辑:

深入挖掘,我们可以看到问题源于以下行为的差异collect:

在2.9.2中:

scala> Set(1).collect { case w => w }
res1: scala.collection.immutable.Set[Int] = Set(1)
Run Code Online (Sandbox Code Playgroud)

在2.10.0中:

scala> Set(1).collect { case w => w }
res4: scala.collection.immutable.Set[_ <: Int] = Set(1)
Run Code Online (Sandbox Code Playgroud)

据推测,原因在于Set,与例如List类型不变的事实不同.但是更完整的解释,特别是给出这种变化动机的解释,将会很棒.

psp*_*psp 6

这是一个错误.您也可以通过键入模式来解决它,如

scala> Set(1).collect { case w => w }
res0: scala.collection.immutable.Set[_ <: Int] = Set(1)

scala> Set(1).collect { case w: Int => w }
res1: scala.collection.immutable.Set[Int] = Set(1)
Run Code Online (Sandbox Code Playgroud)