我正在将一些代码从2.9转换为2.10,并遇到意外的编译错误。这是最小的形式:
在2.9.2中,这很好用:
scala> List(1).flatMap(n => Set(1).collect { case w => w })
res0: List[Int] = List(1)
在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 })
^
但如果我明确地将内部结果转换为List
或明确指定flatmap
的泛型类型,那么它在2.10.0中可以正常工作:
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)
有人可以向我解释2.10的变化导致类型推断在2.9中没有失败吗?
修改
深入挖掘,我们可以看到问题源于collect
行为的差异:
在2.9.2中:
scala> Set(1).collect { case w => w }
res1: scala.collection.immutable.Set[Int] = Set(1)
在2.10.0中:
scala> Set(1).collect { case w => w }
res4: scala.collection.immutable.Set[_ <: Int] = Set(1)
据推测,原因与Set
不同,例如List
不是类型不变的事实。但是更完整的解释,特别是给出这种改变动机的解释,将会很棒。
答案 0 :(得分:6)
这是一个bug。您也可以通过键入模式来解决它,如
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)